一、MySQL BLOB
类型
BLOB
- MySQL中,
是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。BLOB
- 插入
类型的数据必须使用BLOB
,因为PreparedStatement
类型的数据无法使用字符串拼接写的。BLOB
- MySQL的四种
类型(除了在存储的最大信息量上不同外,他们是等同的)。BLOB
MySQL数据库操作Blob类型字段一、MySQL BLOB类型二、用PreparedStatement操作Blob类型的数据 - 实际使用中根据需要存入的数据大小定义不同的
类型。BLOB
- 如果存储的文件过大,数据库的性能会下降。
- 如果在指定了相关的
类型以后,还报错Blob
,那么在mysql的安装目录下,找xxx too large
文件加上如下的配置参数:my.ini
。同时注意:修改了max_allowed_packet=16M
文件之后,需要重新启动mysql服务。my.ini
二、用PreparedStatement操作Blob类型的数据
插入
Blob
类型的字段数据
//使用PreparedStatement操作Blob类型的数据
public class BlobTest {
//向数据表customers中插入Blob类型的字段数据
@Test
public void testInsert(){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();
String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1,"李四");
preparedStatement.setObject(2,"[email protected]");
preparedStatement.setObject(3,"2021-04-03");
FileInputStream fileInputStream = new FileInputStream(new File("图片.png"));
preparedStatement.setBlob(4,fileInputStream);
preparedStatement.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(connection,preparedStatement);
}
}
}
读取
Blob
类型的字段数据
//读取Blob类型字段数据
@Test
public void testQuery(){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
InputStream photoBinaryStream = null;
FileOutputStream fileOutputStream = null;
try {
connection = JDBCUtils.getConnection();
String sql = "select id,name,email,birth,photo from customers where id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,22);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
Date birth = resultSet.getDate("birth");
Customer customer = new Customer(id, name, email, birth);
System.out.println(customer);
//将Blob类型的字段数据下载下来,以文件的方式保存在本地
Blob photo = resultSet.getBlob("photo");
photoBinaryStream = photo.getBinaryStream();
fileOutputStream = new FileOutputStream(new File("photo1.png"));
byte[] buffer = new byte[1024];
int len;
while((len = photoBinaryStream.read(buffer)) != -1){
fileOutputStream.write(buffer,0,len);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null)
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (photoBinaryStream != null)
photoBinaryStream.close();
} catch (IOException e) {
e.printStackTrace();
}
JDBCUtils.closeResource(connection,preparedStatement,resultSet);
}
}