Blob类型的数据的操作
Blob类型:2进制大数据
四种Blob类型:
-
TinyBlob:最大255(字节)
-
Blob:最大65K
-
MediumBlob:最大16M
-
LongBlob:最大4G
根据数据大小选择相应的大小
向数据表中插入Blob类型的数据
//向数据表插入Blob类型字段
@Test
public void testInsert() throws Exception {
Connection conn = JdbcUtils.getConnection();
String sql = "insert into blobtest (username,password,photo) values (?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1,"why");
ps.setObject(2,"123");
FileInputStream is = new FileInputStream(new File("D:\photo\anglebaby.jpg"));
ps.setBlob(3,is);
ps.execute();
JdbcUtils.closeResource(conn,ps);
}
查询数据表中的Blob类型的数据
//查询数据
@Test
public void testQuery() {
InputStream is = null;
FileOutputStream fos = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "select photo from blobtest where id = ?";
ps = conn.prepareStatement(sql);
ps.setObject(1,1);
rs = ps.executeQuery();
if (rs.next()){
//方式一:
// Blob photo = rs.getBlob(1);
//方式二:
Blob photo = rs.getBlob("photo");
//下载以文件的方式保存至本低
is = photo.getBinaryStream();
fos = new FileOutputStream("D:\word\anglebaby.jpg");
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
JdbcUtils.closeResource(conn,ps,rs);
try {
is.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}