BLOB是MySQL中的数据类型,在Oracle中类型稍有不同,但是原理一致。
MySQL的四种BLOB类型(单位:字节)
TinyBlob 最大 255,Blob 最大 65K,MediumBlob 最大16M,LongBlob 最大 4G
由于BLOB的数据时无法用字符串拼装的,所以插入BLOB类型的数据必须使用PreparedStatement。
本文中举例说明通过JDBC来操作BLOB的方法。
插入BLOB数据
如下所示,其中DBTools是自己完成的静态库,用于操作数据库。
public static void blobInsertTest() throws Exception{
InputStream is = new FileInputStream("E:\\test.jpg");
Connection conn = DBTools.getConnection();
String sql = "insert into student (photo) value (?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setBlob(1, is);
ps.executeUpdate();
is.close();
DBTools.release(null, ps, conn);
}
取出BLOB数据
取出BLOB图片,将其另存到磁盘中。
public static void blobSelectTest() throws Exception{
Connection conn = DBTools.getConnection();
String sql = "select photo from student where id = 12";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
Blob blob = rs.getBlob("photo");
InputStream is = blob.getBinaryStream();
FileOutputStream fos = new FileOutputStream("E:\\test2.jpg");
byte[] photoData = new byte[1024];
while(is.read(photoData) != -1){
fos.write(photoData);
}
is.close();
fos.close();
}
DBTools.release(rs, ps, conn);
}
在插入数据时,获取当前插入数据对应的主键举例
public static void update() throws Exception{
Connection conn = DBTools.getConnection();
String sql = "insert into student (name) values('username')";
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
while(rs.next())
{
System.out.println("PrimaryKey:" + rs.getObject(1));
}
}
<完>