【JDBC】操作BLOB类型字段

1.Blob类型

  • MySQL中Blob是一个二进制大型对象,可以存储大量数据的容器,能容纳不同大小的数据。
  • 插入Blob类型的数据必须使用PrepareStatement,因为Blob类型的数据无法使用字符串拼接写的。
  • 四种Blob类型除了存储的最大信息量上不同,其他都是相同的。
类型 大小(单位:字节)
TinyBlob 最大255
Blob 最大65K
MediumBlob 最大16M
LongBlob 最大4G
  • 实际使用中根据需要存入的数据大小定义不同的Blob类型。
  • 如果存储的文件过大,数据库的性能会下降。
  • 如果在指定了相关的Blob类型后,还报错:xxx to large,在mysql的安装目录下,找到my.ini文件加上:max_allowed_packet = 16M。保存后重启mysql服务。

2.向数据库中插入Blob类型数据

image

    @Test
    public int updateCustomer() throws Exception {
        Connection connect = JDBCUtil.getConnection();
        String sql = "insert into customers(name,email,birth,photo) value(?,?,?,?)";
        PreparedStatement ps = connect.prepareStatement(sql);
        
        ps.setString(1, "张三");
        ps.setString(2, "zhangsan@163.com");
        ps.setDate(3, new java.sql.Date(new Date().getTime()));
        FileInputStream fis = new FileInputStream(new File("girl.jpg"));
        ps.setBlob(4, fis);

        int updateColumn = ps.executeUpdate();
        fis.close();
        JDBCUtil.closeResource(connect, ps);
        return updateColumn;
    }

图片在项目路径下,与src同级
image

修改操作改一下SQL和文件。

3.查询Blob类型字段

把数据库图片下载到本地

    public void queryCustomer() {
        Connection connect = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            connect = JDBCUtil.getConnection();
            String sql = "select id,name,email,birth,photo from customers where id = ?";
            ps = connect.prepareStatement(sql);
            ps.setInt(1, 21);
            rs = ps.executeQuery();
            if (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String email = rs.getString("email");
                Date birth = rs.getDate("birth");

                Customer customer = new Customer(id, name, email, birth);
                System.out.println(customer.toString());

                Blob photo = rs.getBlob("photo");
                is = photo.getBinaryStream();
                fos = new FileOutputStream("downFile.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 {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            JDBCUtil.closeResource(connect, ps, rs);
        }
    }

下载在当前项目下
image

posted @ 2022-11-17 14:29  植树chen  阅读(102)  评论(0编辑  收藏  举报