首页 > 代码库 > jdbc插入大对象及读取大对象

jdbc插入大对象及读取大对象

 1 /**
 2  * 插入大对象
 3  */
 4     @Test
 5     public void testSavePic(){
 6         Connection conn=null;
 7         Statement st=null;
 8         PreparedStatement pst=null;
 9         try {
10             conn=DBUtils.getConn();
11             conn.setAutoCommit(false);//事物不能自动提交
12             st=conn.createStatement();
13             long start = System.currentTimeMillis();
14             String sql="insert into stu(sid,name,pic,info) values(?,?,?,?)";
15             pst=conn.prepareStatement(sql);
16             pst.setInt(1, 1);
17             pst.setString(2, "tim");
18             //设置大对象
19             File file =new File("D:\\arch\\unarch/b.jpg");
20             FileInputStream fis = new FileInputStream(file);
21             pst.setBinaryStream(3, fis,file.length());//设置二进制流,指定长度
22             pst.setString(4, "xxxxxx");
23             pst.executeUpdate();
24              conn.commit();//提交事务
25              System.out.println(System.currentTimeMillis()-start);
26         } catch (Exception e) {
27             // TODO Auto-generated catch block
28             e.printStackTrace();
29         }
30         finally{
31             DBUtils.closeAll(null, st, conn);
32         }
33     }

2、读取大对象

 1 /**
 2  * 对取大对象
 3  */
 4     @Test
 5     public void testReadPic(){
 6         Connection conn=null;
 7         Statement st=null;
 8         PreparedStatement pst=null;
 9         try {
10             conn=DBUtils.getConn();
11             conn.setAutoCommit(false);//事物不能自动提交
12             st=conn.createStatement();
13             long start = System.currentTimeMillis();
14             String sql="select pic from stu where sid=?";
15             pst=conn.prepareStatement(sql);
16             pst.setInt(1, 1);
17             ResultSet rs = pst.executeQuery();
18             if(rs.next()){
19                 byte[] bytes = rs.getBytes(1);
20                 FileOutputStream fos = new FileOutputStream("d:/kk.jpg");
21                 fos.write(bytes);
22                 fos.close();
23             }
24                     
25              conn.commit();//提交事务
26              System.out.println("over");
27              System.out.println(System.currentTimeMillis()-start);
28         } catch (Exception e) {
29             // TODO Auto-generated catch block
30             e.printStackTrace();
31         }
32         finally{
33             DBUtils.closeAll(null, st, conn);
34         }
35     }

 

jdbc插入大对象及读取大对象