首页 > 技术文章 > <十>JDBC_处理Blob类型数据

iamkk 2016-11-22 20:45 原文

 /*
  * 读取BLOB数据:
  *  使用getBlob方法读取到Blob对象
  *  调用Blob的getBinaryStream(方法得到输入流,在使用IO操作
  * */
 @Test
 public void readBlob(){
  
  Connection conn=null;
  PreparedStatement ps=null;
  ResultSet rs=null;
  try {
   conn=JDBCTools.getConnection();
   String sql="select * from customers where id=8";
   ps=conn.prepareStatement(sql);
   rs=ps.executeQuery();
   if (rs.next()) {
    int id=rs.getInt(1);
    String name=rs.getString(2);
    String email=rs.getString(3);
    Blob picture=rs.getBlob(5);
    InputStream in=picture.getBinaryStream();
    OutputStream os=new FileOutputStream("xrk.jpg");
    byte[] buffer=new byte[1024];
    int len=0;
    while((len=in.read(buffer))!=-1){
     os.write(buffer, 0, len);
    }
    os.close();
    in.close();
    System.out.println(id+"  "+name+" "+email);
   }
   
  } catch (Exception e) {
   e.printStackTrace();
  }finally{
   JDBCTools.release(rs, ps, conn);
  }
 }
 
 /*
  * 插入BLOB类型的数据必须使用PreparedStatement:因为BLOB类型的数据是无法使用字符串拼写的
  * */
 @Test
 public void testInsertBlob(){
  
  Connection conn=null;
  PreparedStatement ps=null;
  
  try {
   
  conn=JDBCTools.getConnection();
  String sql="insert into customers (name,email,birth,picture)values(?,?,?,?)";
  ps=conn.prepareStatement(sql);
  ps.setString(1, "zpy");
  ps.setString(2, "zpy@.com");
  ps.setDate(3, new Date(new java.util.Date().getTime()));
  InputStream is=new FileInputStream("kk.jpg");
  ps.setBlob(4, is);
  ps.executeUpdate();
  
  } catch (Exception e) {
   JDBCTools.release(null, ps, conn);
  }
 }

 

推荐阅读