JDBCJ技术(七)——MySQL BLOB

一、简介:

MySQL 中, BLOB 是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。

二、MySQL的四种BLOB类型

 

三、BLOB具体实例

1.向数据库中插入BLOB类型的数据

例:插入一张图片

 /**
     * 插入 BLOB 类型的数据 必须使用 prepareStatement:因为 BLOB类型
     * 的数据是无法使用字符串拼写的
     */
    @Test
    public void testInsertBlob() {
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        try {

            conn = JDBCTools.getConnection();
            String sql = "INSERT INTO customers(name,email,brith,picture)" +
                    "VALUES(?,?,?,?)";
            preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1, "AasdasdqE");
            preparedStatement.setString(2, "8971646321354@qq.com");
            preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
            InputStream inputStream = new FileInputStream("桌面2.jpg");
            preparedStatement.setBlob(4, inputStream);
            preparedStatement.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCTools.release(null, preparedStatement, conn);
        }


    }

插入前

插入后

注: 插入 BLOB 类型的数据 必须使用 prepareStatement:因为 BLOB类型的数据是无法使用字符串拼写的


2.读取BLOB

/**
     * 读取BLOB
     */
    @Test
    public void readBlob() {
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;


        try {

            conn = JDBCTools.getConnection();
            String sql = "SELECT *" + "FROM customers WHERE  id = 11";
            preparedStatement = conn.prepareStatement(sql);
            rs = preparedStatement.executeQuery();

            if (rs.next()) {
                int id = rs.getInt(1);
                String name = rs.getString(2);
                String email = rs.getString(3);

                System.out.println(id + "," + name + "," + email);

                Blob picture = rs.getBlob(5);
                InputStream in = picture.getBinaryStream();
                OutputStream out = new FileOutputStream("ecplise.jpg");
                byte[] bufr = new byte[1024];
                int len = 0;
                while ((len = in.read(bufr)) != -1) {
                    out.write(bufr, 0, len);
                }
                out.close();
                in.close();
            }


        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            JDBCTools.release(rs, preparedStatement, conn);
        }

结果截图:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值