四、操作BLOB類型字段
4.1 MySQL BLOB類型
-
MySQL中,BLOB是一個二進制大型對象,是一個可以存儲大量數據的容器,它能容納不同大小的數據。
-
插入BLOB類型的數據必須使用PreparedStatement,因為BLOB類型的數據無法使用字符串拼接寫的。
-
MySQL的四種BLOB類型(除了在存儲的最大信息量上不同外,他們是等同的)
- 實際使用中根據需要存入的數據大小定義不同的BLOB類型。
- 需要注意的是:如果存儲的文件過大,數據庫的性能會下降。
- 如果在指定了相關的Blob類型以后,還報錯:xxx too large,那么在mysql的安裝目錄下,找my.ini文件加上如下的配置參數: max_allowed_packet=16M。同時注意:修改了my.ini文件之后,需要重新啟動mysql服務。
4.2 向數據表中插入大數據類型
@Test
public void testInsert() throws Exception {
Connection conn = JDBCUtils.getConnection();
String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1, "xiaoran");
ps.setObject(2, "xiaoran@qq.com");
ps.setObject(3, "2000-10-9");
FileInputStream is = new FileInputStream(new File("mao.jpg"));
ps.setBlob(4, is);
ps.execute();
JDBCUtils.closeResource(conn, ps, null);
}
4.3 修改數據表中的Blob類型字段
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 從數據表中讀取大數據類型
@Test
public void testQuery() throws Exception {
Connection conn = JDBCUtils.getConnection();
String sql = "select id,name,email,birth,photo from customers where name = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1, "xiaoran");
InputStream is = null;
FileOutputStream fos = null;
ResultSet rs = ps.executeQuery();
if(rs.next()){
//方式一:
// int id = rs.getInt(1);
// String name = rs.getString(2);
// String email = rs.getString(4);
// Date birth = rs.getDate(4);
//方式二:
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
Date birth = rs.getDate("birth");
Customer customer = new Customer(id, name, email, birth);
System.out.println(customer);
Blob photo = rs.getBlob("photo");
is = photo.getBinaryStream();
fos = new FileOutputStream("maomao.jpg");
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
fos.write(buffer, 0, len);
}
}
is.close();
fos.close();
JDBCUtils.closeResource(conn, ps, rs);
}