一、简介:
MySQL 中, BLOB 是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。
二、MySQL的四种BLOB类型
三、BLOB具体实例
1.向数据库中插入BLOB类型的数据
例:插入一张图片
/**
* 插入 BLOB 类型的数据 必须使用 prepareStatement:因为 BLOB类型
* 的数据是无法使用字符串拼写的
*/
@Test
public void testInsertBlob() {
Connection conn = null;
PreparedStatement preparedStatement = null;
try {
conn = JDBCTools.getConnection();
String sql = "INSERT INTO customers(name,email,brith,picture)" +
"VALUES(?,?,?,?)";
preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "AasdasdqE");
preparedStatement.setString(2, "8971646321354@qq.com");
preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
InputStream inputStream = new FileInputStream("桌面2.jpg");
preparedStatement.setBlob(4, inputStream);
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.release(null, preparedStatement, conn);
}
}
插入前
插入后
注: 插入 BLOB 类型的数据 必须使用 prepareStatement:因为 BLOB类型的数据是无法使用字符串拼写的
2.读取BLOB
/**
* 读取BLOB
*/
@Test
public void readBlob() {
Connection conn = null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try {
conn = JDBCTools.getConnection();
String sql = "SELECT *" + "FROM customers WHERE id = 11";
preparedStatement = conn.prepareStatement(sql);
rs = preparedStatement.executeQuery();
if (rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
String email = rs.getString(3);
System.out.println(id + "," + name + "," + email);
Blob picture = rs.getBlob(5);
InputStream in = picture.getBinaryStream();
OutputStream out = new FileOutputStream("ecplise.jpg");
byte[] bufr = new byte[1024];
int len = 0;
while ((len = in.read(bufr)) != -1) {
out.write(bufr, 0, len);
}
out.close();
in.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.release(rs, preparedStatement, conn);
}
结果截图: