•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();