JDBC之CLOB与BLOB

今天我们来介绍一下CLOB与BLOB的存储与读取。那么CLOB和BLOB是什么呢?
CLOB:大字符数据,例如长篇小说
BLOB:二进制数据,例如图片、视频
首先我们定义一个新表:

create table `t_lob` (
    `id` int (11),
    `context` text ,
    `pic` blob 
); 

下面我们将分别对长文本和图片进行读取和存储。根据面向对象的思想,我们建立Lob类:

public class Lob {
    private File context;
    private File pic;
    //构造方法,get和set方法省略
}

下面我们将小说和图片写入到数据库,二话不说直接上代码:

    private static int addContext(Lob lob) throws Exception {
        Connection con = dbUtil.getCon();
        String sql = "insert into t_lob values(null,?,?)";
        PreparedStatement pstmt = con.prepareStatement(sql);

        // 存小说
        File context = lob.getContext();
        InputStream inputStream = new FileInputStream(context);
        pstmt.setAsciiStream(1, inputStream, context.length());

        // 存图片
        File pic = lob.getPic();
        InputStream inputStream2 = new FileInputStream(pic);
        pstmt.setBinaryStream(2, inputStream2, pic.length());

        int result = pstmt.executeUpdate();
        dbUtil.close(pstmt, con);
        return result;
    }

这里都是以流的形式进行的存储。那么我们如何将这些数据从数据库中读取出来呢?

    public static void getContext(int id) throws Exception {
        Connection con = dbUtil.getCon();
        String sql = "select * from t_lob where id=?";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setInt(1, id);
        ResultSet rs = pstmt.executeQuery();
        if (rs.next()) {
            //读小说
            Clob clob = rs.getClob("context");
            String context = clob.getSubString(1, (int) clob.length());
            System.out.println(context);

            //读图片
            Blob blob = rs.getBlob("pic");
            FileOutputStream out = new FileOutputStream(new File("E:/pic.jpg"));
            out.write(blob.getBytes(1, (int) blob.length()));
            out.close();
        }
        rs.close();
        dbUtil.close(pstmt, con);
    }

这就是我们本章要讲的内容。后面会有更精彩的内容等着你们!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值