JDBC(四)—— Blob类型操作

Blob类型的数据的操作

Blob类型:2进制大数据

四种Blob类型:

  1. TinyBlob:最大255(字节)

  2. Blob:最大65K

  3. MediumBlob:最大16M

  4. LongBlob:最大4G

根据数据大小选择相应的大小

向数据表中插入Blob类型的数据

//向数据表插入Blob类型字段
@Test
public void testInsert() throws Exception {
   Connection conn = JdbcUtils.getConnection();
   String sql = "insert into blobtest (username,password,photo) values (?,?,?)";
   PreparedStatement ps = conn.prepareStatement(sql);
   ps.setObject(1,"why");
   ps.setObject(2,"123");
   FileInputStream is = new FileInputStream(new File("D:\\photo\\anglebaby.jpg"));
   ps.setBlob(3,is);
   ps.execute();
   JdbcUtils.closeResource(conn,ps);
}

查询数据表中的Blob类型的数据

//查询数据
@Test
public void testQuery() {
   InputStream is = null;
   FileOutputStream fos = null;
   Connection conn = null;
   PreparedStatement ps = null;
   ResultSet rs = null;
   try {
       conn = JdbcUtils.getConnection();
       String sql = "select photo from blobtest where id = ?";
       ps = conn.prepareStatement(sql);
       ps.setObject(1,1);
       rs = ps.executeQuery();
       if (rs.next()){
           //方式一:
//           Blob photo = rs.getBlob(1);
           //方式二:
           Blob photo = rs.getBlob("photo");
           //下载以文件的方式保存至本低
           is = photo.getBinaryStream();
           fos = new FileOutputStream("D:\\word\\anglebaby.jpg");
           byte[] buffer = new byte[1024];
           int len;
           while ((len = is.read(buffer))!=-1){
               fos.write(buffer,0,len);
          }
      }
  } catch (Exception e) {
       e.printStackTrace();
  }finally {
       JdbcUtils.closeResource(conn,ps,rs);
       try {
           is.close();
           fos.close();
      } catch (IOException e) {
           e.printStackTrace();
      }
  }

}

 

posted @ 2020-12-14 20:07  笔落惊风  阅读(219)  评论(0编辑  收藏  举报