复习课程jdbc:使用配置文件properties进行连接数据库,数据库存取图片,批处理,时间戳,事物回滚等等

使用配置文件properties进行连接数据库

首先创建一个file自定义文件名,但是后缀名必须改为.properties(不分大小写):如config.properties;

然后双击config.properties进行编辑:此文件数据是根据键值对来存储的:我们可以把连接数据库的一些连接字符串存储在此文件里;然后用的时候直接读配置文件,到时候更换的时候方便移植和修改。

name                                                                               value

driver                                                                               com.microsoft.sqlserver.jdbc.SQLServerDriver

con                                                                                  jdbc:sqlserver://localhost:1433;databaseName=Test

user                                                                                 sa

pwd                                                                

然后用的时候:

public class TestMain {
     Connection con=null;
     Properties pro=new Properties();
     public TestMain() throws IOException, ClassNotFoundException, SQLException
     {
      pro.load(TestMain.class.getClassLoader().getResourceAsStream("config.properties"));
      //加载驱动
      Class.forName(pro.getProperty("driver"));
      //创建连接
      con=DriverManager.getConnection(pro.getProperty("con"),pro.getProperty("user"),pro.getProperty("pwd"));
     
     }

  //测试上传图片

   @Test
    public void setImg() throws SQLException, FileNotFoundException{
     String sql="INSERT INTO [Test].[dbo].[User]([name],[age],[image])VALUES(?,?,?)";
     PreparedStatement ps=con.prepareStatement(sql);
     ps.setObject(1,"测试name");
     ps.setObject(2,22);
     FileInputStream fis=new FileInputStream(new File("D:\img\Picture1.jpg"));//从D盘Img读取
     ps.setBinaryStream(3,fis);
     int num=ps.executeUpdate();
     System.out.println("num为:"+num);  
    }

    //取图片并写入到硬盘文件夹
    @Test
    public void getIma() throws SQLException, IOException{
      Statement state=con.createStatement();
     String sql="select [image] from [User] where id=6";
     ResultSet rs=state.executeQuery(sql);
     rs.next();
     InputStream input=rs.getBinaryStream(1);
     OutputStream out=new FileOutputStream("D:\15.jpg");//写入到D盘
     byte[] bte=new byte[1024];
     int length=0;
     while((length=input.read(bte))>0){
      out.write(bte,0,length);
     }
     input.close();
     out.close();
    }

//批处理:测试时,使用批处理比使用循环.executeUpdate()节省大概一半时间
    @Test
    public void useBatch() throws SQLException{
     String sql="INSERT INTO [Test].[dbo].[User]([name],[age])VALUES(?,?)";
     PreparedStatement ps=con.prepareStatement(sql);
     long noe=System.currentTimeMillis();
     for (int j = 0; j < 10000; j++) {
      ps.setObject(1,"sp"+j);
         ps.setObject(2,j);
         //ps.executeUpdate();原时间为5875毫秒
         ps.addBatch();
         
  }
     ps.executeBatch();
     
     System.out.println("增加10000次的时间为:"+(System.currentTimeMillis()-noe));  
    }

 //时间戳
    @Test
    public void testDate() throws SQLException{
     String sql="INSERT INTO [Test].[dbo].[User]([name],[age],[startTime],[endTime])VALUES(?,?,?,?)";
     PreparedStatement ps=con.prepareStatement(sql);
     ps.setString(1,"测试名");
     ps.setInt(2,20);
     ps.setTimestamp(3,new Timestamp(System.currentTimeMillis()));
     ps.setDate(4,new Date(System.currentTimeMillis()));//这个Date是.sql包下的,不是.util包下的,莫导错包了!
     int zong=ps.executeUpdate();
     System.out.println("时间戳"+zong);   

}

    //测试回滚不提交
    @Test
    public void testTransaction() throws SQLException{
        con.setAutoCommit(false);//设置默认不自动提交
        try {
         String sql="update [User] set money=money-100 where id=5";
         Statement state=con.createStatement();
         state.executeUpdate(sql);
         //int a=10/0;
         sql="update [User] set money=money+100 where id=1";
         state.executeUpdate(sql);
         con.commit();//提交事务
  } catch (Exception e) {
   con.rollback();
  }
    //用jdbc同样可以实现事物回滚!如果没有设置默认不自动提交,那么执行到int a=10/0;就不向下执行了,转账会出现扣钱,没加钱的错误!
    }

}

还有,这里在执行读取操作的时候,用到了 rs.getMetaData().getColumnCount();和rs.getMetaData().getColumnName()很有用;

 private List<Map<String,Object>> setMap() throws SQLException{
      List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
      Statement state=con.createStatement();
      
      String sql="select * from [User]";
   ResultSet rs=state.executeQuery(sql);
   while(rs.next()){
    Map<String,Object> map=new HashMap<String, Object>();
    for (int i = 1; i <=rs.getMetaData().getColumnCount(); i++) {
    map.put(rs.getMetaData().getColumnName(i),rs.getObject(i));
    }
          list.add(map);
   }  
      rs.close();
      state.close();
      con.close();
   return list;
     }
     @Test
     public void getMap() throws SQLException{
      List<User> users=new ArrayList<User>();
      List<Map<String,Object>> list=setMap();
      for (Map<String, Object> map : list) {
       User user=new User();
    user.setAge(Integer.valueOf((map.get("age").toString())));
    user.setId(Integer.valueOf((map.get("id").toString())));
    user.setName(map.get("name").toString());
    users.add(user);
  }
     
      for (User item : users) {
   p(item.getId()+" "+item.getAge()+" "+item.getName());
  }
     }
    
    
    
    
     @Test
     public void getList() throws SQLException{
      List<List> list=setList();
      for (List list2 : list) {
   for (Object object : list2) {
    p(object);
   }
  }
     }
    private List<List> setList() throws SQLException{
     Statement state=con.createStatement();
     List<List> list=new ArrayList<List>();
     String sql="select * from [User]";
  ResultSet rs=state.executeQuery(sql);
  while(rs.next()){
   List l=new ArrayList();
   for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
   l.add(rs.getObject(i));
   }
         list.add(l);
  }  
     rs.close();
     state.close();
     con.close();
  return list;
     
    }

 

原文地址:https://www.cnblogs.com/345214483-qq/p/3967310.html