前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JDBC 处理Blob(10)

JDBC 处理Blob(10)

作者头像
桑鱼
发布2020-03-17 15:37:00
9140
发布2020-03-17 15:37:00
举报

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

MySQL 的四种Blob类型:(除了在存储的最大信息量上不同外,它们是等同的,如果存储的文件过大,数据库的性能会下降)

类型

大小(单位:字节)

TinyBlob

最大 255byte

Blob

最大 65k

MediumBlob

最大 16M

LongBlob

最大 4G

public class JDBCTest03 {
    // 插入图片,在数据库设置对应图片字段的Blob类型
    // 插入Blob类型的数据必须使用PreparedStatement,因为Blob类型的数据无法使用字符串拼写
    public void testInsertBlob() throws ClassNotFoundException, SQLException, FileNotFoundException {
        String sql = "INSERT INTO customers(name, email, birth, picture)"
                + "VALUES(?,?,?,?)";
        String driverClass = "com.mysql.jdbc.Driver";
        String jdbcurl = "";
        Class.forName(driverClass);
        Connection connection = DriverManager.getConnection(jdbcurl,"user","password");
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        InputStream inputStream = new FileInputStream("picture.jpg");
        preparedStatement.setBlob(4,inputStream);
        preparedStatement.executeUpdate();

        preparedStatement.close();
        connection.close();
    }

    // 读取图片
    // 读取blob数据:
    // 1. 使用getBlob方法读取到Blob对象
    // 2.调用Blob的getBinaryStream()方法得到输入流。再使用IO操作即可
    public void readBlob() throws ClassNotFoundException, SQLException, IOException {
        String sql = "SELECT id, name customerName, email, birth, picture "
                + "FROM customers WHERE id = 13";
        String driverClass = "com.mysql.jdbc.Driver";
        String jdbcurl = "";
        Class.forName(driverClass);
        Connection connection = DriverManager.getConnection(jdbcurl,"user","password");
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        if(resultSet.next()){
            int id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            String email = resultSet.getString(3);
            Blob picture = resultSet.getBlob(5);

            InputStream in = picture.getBinaryStream();

            OutputStream out = new FileOutputStream("newPicture.jpg");
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1){
                out.write(buffer,0,len);
            }
            in.close();
            out.close();
        }
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }    
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
对象存储
对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档