I:向数据表中的Blob类型的字段插入数据
为简洁查看,这里使用 throws 解决异常,若在使用中,以下代码的异常应该使用 try-catch-finally 处理
public void testInsertBlob() throws Exception {
Connection conn = JDBCUtils.getConnection();
String sql = "insert into customers(photo) values(?)";
PreparedStatement ps = conn.prepareStatement(sql);
FileInputStream fis = new FileInputStream(new File("girl.jpg"));
ps.setBlob(1, fis);
ps.execute();
fis.close();
JDBCUtils.closeResource(conn, ps);
}
I:查询数据表中的Blob类型的字段的数据
为简洁查看,这里使用 throws 解决异常,若在使用中,以下代码的异常应该使用 try-catch-finally 处理
public void testQueryBlob() throws Exception {
Connection conn = JDBCUtils.getConnection();
String sql = "select photo from customers where id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1, 31);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
Blob photo = rs.getBlob("photo");
InputStream is = photo.getBinaryStream();
FileOutputStream fos = new FileOutputStream("2.jpg");
byte[] bBuffer = new byte[1024];
int len;
while ((len = is.read(bBuffer)) != -1) {
fos.write(bBuffer, 0, len);
}
fos.close();
is.close();
}
JDBCUtils.closeResource(conn, ps);
}