MySQL BLOB 是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。
MySQL 的四种BLOB类型
TinyBLOB:最大255
BLOB:最大 65K
MediumBLOB:最大 16M
LongBLOB:最大 4G
/**
* 查询数据表中的 Blob 类型的字段
*/
public void testQuery(){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
InputStream is = null;
FileOutputStream fos = null;
try {
//获取数据库连接
connection = JDBCTools.getConnection();
//准备SQL语句
String sql = "select name,address,picture from customers where id = ?";
preparedStatement = connection.prepareStatement(sql);
//填充占位符
preparedStatement.setInt(1, 44);
//查询操作
rs = preparedStatement.executeQuery();
if(rs.next()){
//获取结果集并封装对象
String name = rs.getString(1);
String address = rs.getString(2);
Customer customer = new Customer(name, address);
System.out.println(customer);
//使用 getBlob() 方法读取到 Blob 对象
Blob picture = rs.getBlob(3);
//调用 Blob 的 getBinaryStream() 方法得到输入流
is = picture.getBinaryStream();
//将得到的图片通过字节流下载到本地
fos = new FileOutputStream("123.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{
JDBCTools.release(rs, preparedStatement, connection);
}
}