Manipulate BLOB type fields
4.1 MySQL BLOB type
-
In MySQL, BLOB is a large binary object, a container that can store a large amount of data, and it can hold data of different sizes.
-
Inserting BLOB type data must use PreparedStatement, because BLOB type data cannot be written using string concatenation.
-
MySQL's four BLOB types (except for the difference in the maximum amount of information stored, they are equivalent)
- In actual use, different BLOB types are defined according to the size of the data to be stored.
- It should be noted that if the stored file is too large, the performance of the database will decrease.
- If after specifying the relevant Blob type, an error is reported: xxx too large, then in the mysql installation directory, find the my.ini file and add the following configuration parameters: max_allowed_packet=16M . At the same time note: After modifying the my.ini file, you need to restart the mysql service.
4.2 Insert large data types into the data table
//获取连接
Connection conn = JDBCUtils.getConnection();
String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
// 填充占位符
ps.setString(1, "徐海强");
ps.setString(2, "[email protected]");
ps.setDate(3, new Date(new java.util.Date().getTime()));
// 操作Blob类型的变量
FileInputStream fis = new FileInputStream("xhq.png");
ps.setBlob(4, fis);
//执行
ps.execute();
fis.close();
JDBCUtils.closeResource(conn, ps);
4.3 Modify the Blob type field in the data table
Connection conn = JDBCUtils.getConnection();
String sql = "update customers set photo = ? where id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
// 填充占位符
// 操作Blob类型的变量
FileInputStream fis = new FileInputStream("coffee.png");
ps.setBlob(1, fis);
ps.setInt(2, 25);
ps.execute();
fis.close();
JDBCUtils.closeResource(conn, ps);
4.4 Reading large data types from the data table
String sql = "SELECT id, name, email, birth, photo FROM customer WHERE id = ?";
conn = getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, 8);
rs = ps.executeQuery();
if(rs.next()){
Integer id = rs.getInt(1);
String name = rs.getString(2);
String email = rs.getString(3);
Date birth = rs.getDate(4);
Customer cust = new Customer(id, name, email, birth);
System.out.println(cust);
//读取Blob类型的字段
Blob photo = rs.getBlob(5);
InputStream is = photo.getBinaryStream();
OutputStream os = new FileOutputStream("c.jpg");
byte [] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer)) != -1){
os.write(buffer, 0, len);
}
JDBCUtils.closeResource(conn, ps, rs);
if(is != null){
is.close();
}
if(os != null){
os.close();
}
}