您的位置:首页 > 其它

JDBC之CLOB与BLOB

2016-07-22 23:01 337 查看
今天我们来介绍一下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);
}


这就是我们本章要讲的内容。后面会有更精彩的内容等着你们!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jdbc