jdbc 读写 blob 类型的数据

830阅读 0评论2021-05-07 fhadmin
分类:Java


1 MySQL BLOB类型
MySQL中,BLOB是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。
插入BLOB类型的数据必须使用PreparedStatement,因为BLOB类型的数据无法使用字符串拼接写的。
MySQL的四种BLOB类型(除了在存储的最大信息量上不同外,他们是等同的)点击并拖拽以移动
实际使用中根据需要存入的数据大小定义不同的BLOB类型。
需要注意的是:如果存储的文件过大,数据库的性能会下降。
如果在指定了相关的Blob类型以后,还报错:xxx too large,那么在mysql的安装目录下,找my.ini文件加上如下的配置参数: max_allowed_packet=16M。同时注意:修改了my.ini文件之后,需要重新启动mysql服务。
2 向数据表中插入大数据类型

点击(此处)折叠或打开

  1. //获取连接
  2. Connection conn = JDBCUtils.getConnection();
  3.         
  4. String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?)";
  5. PreparedStatement ps = conn.prepareStatement(sql);

  6. //java项目www fhadmin org
  7. // 填充占位符
  8. ps.setString(1, "张强");
  9. ps.setString(2, "123@126.com");
  10. ps.setDate(3, new Date(new java.util.Date().getTime()));
  11. // 操作Blob类型的变量
  12. FileInputStream fis = new FileInputStream("xhq.png");
  13. ps.setBlob(4, fis);
  14. //执行
  15. ps.execute();
  16.         
  17. fis.close();
  18. JDBCUtils.closeResource(conn, ps);

3 修改数据表中的Blob类型字段


点击(此处)折叠或打开

  1. Connection conn = JDBCUtils.getConnection();
  2. String sql = "update customers set photo = ? where id = ?";
  3. PreparedStatement ps = conn.prepareStatement(sql);

  4. //java项目www fhadmin org
  5. // 填充占位符
  6. // 操作Blob类型的变量
  7. FileInputStream fis = new FileInputStream("coffee.png");
  8. ps.setBlob(1, fis);
  9. ps.setInt(2, 25);

  10. ps.execute();

  11. fis.close();
  12. JDBCUtils.closeResource(conn, ps);

4 从数据表中读取大数据类型


点击(此处)折叠或打开


  1. String sql = "SELECT id, name, email, birth, photo FROM customer WHERE id = ?";
  2. conn = getConnection();
  3. ps = conn.prepareStatement(sql);
  4. ps.setInt(1, 8);
  5. rs = ps.executeQuery();
  6. if(rs.next()){
  7.     Integer id = rs.getInt(1);
  8.     String name = rs.getString(2);
  9.     String email = rs.getString(3);
  10.     Date birth = rs.getDate(4);
  11.     Customer cust = new Customer(id, name, email, birth);
  12.     System.out.println(cust);
  13.     //读取Blob类型的字段
  14.     Blob photo = rs.getBlob(5);
  15.     InputStream is = photo.getBinaryStream();
  16.     OutputStream os = new FileOutputStream("c.jpg");
  17.     byte [] buffer = new byte[1024];
  18.     int len = 0;
  19.     while((len = is.read(buffer)) != -1){
  20.         os.write(buffer, 0, len);
  21.     }
  22.     JDBCUtils.closeResource(conn, ps, rs);
  23.         
  24.     if(is != null){
  25.         is.close();
  26.     }
  27.         
  28.     if(os != null){
  29.         os.close();
  30.     }
  31.     
  32. }


上一篇:zuul 替代者 微服务网关gateway
下一篇:SpringBoot 项目配置 Swagger 接口api 搭建 REST