•MySQL中,BLOB是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。
•MySQL的四种BLOB类型(除了在存储的最大信息量上不同外,他们是等同的)
类型 | 大小(单位:字节) |
TinyBlob | 最大255 |
Blob | 最大65k |
MediumBlob | 最大16M |
LongBlob | 最大4G |
•实际使用中根据需要存入的数据大小定义不同的BLOB类型。
需要注意的是:如果存储的文件过大,数据库的性能会下降。
插入BLOB类型的数据必须使用PreparedStatement,因为BLOB类型的数据时无法使用字符串拼写。
调用PreparedStatement.setBlob(index,InputStream inputStream)写入数据库。
InputStream inputStream=new FileInputStream("图片名");
调用ResultSet.getBlob(index)得到Blob。
//1.使用getBlob方法读到Blob对象
Blob picture=resultSet.getBlob(5);
//2.调用Blob的getBinaryStream()方法得到输入流,再使用IO操作即可
InputStream in=picture.getBinaryStream();
OutputStream out=new FileOutputStream("flower.jpg");
byte[] buffer=new byte[1024];
int len=0;
while((len=in.read(buffer))!=-1){
out.write(buffer,0,len);
}
out.close();
in.close();