版权声明:本文为小斑马伟原创文章,转载请注明出处!
LOB:即Large Objects(大对象),是用来存储大量的二进制和文本数据的一种数据类型(一个LOB字段可存储可多达4GB的数据)。LOB 分为两种类型:内部LOB和外部LOB。LOB 分为两种类型:内部LOB和外部LOB。
内部LOB将数据以字节流的形式存储在数据库的内部。因而,内部LOB的许多操作都可以参与事务,也可以像处理普通数据一样对其进行备份和恢复操作。Oracle支持三种类型的内部LOB:
- BLOB(二进制数据)
- CLOB(单字节字符数据)
- NCLOB(多字节字符数据)。
CLOB和NCLOB类型适用于存储超长的文本数据,BLOB字段适用于存储大量的二进制数据,如图像、视频、音频,文件等。
目前只支持一种外部LOB类型,即BFILE类型。在数据库内,该类型仅存储数据在操作系统中的位置信息,而数据的实体以外部文件的形式存在于操作系统的文件系统中。因而,该类型所表示的数据是只读的,不参与事务。该类型可帮助用户管理大量的由外部程序访问的文件。
MySQL中,BLOB是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。
MySQL的四种BLOB类型(除了在存储的最大信息量上不同外,他们是等同的)。
实际使用中根据需要存入的数据大小定义不同的BLOB类型。�需要注意的是:如果存储的文件过大,数据库的性能会下降。
插入 BLOB 类型的数据
/**
* 插入 BLOB 类型的数据必须使用 PreparedStatement:因为 BLOB 类型
* 的数据时无法使用字符串拼写的。
*
* 调用 setBlob(int index, InputStream inputStream)
*/
@Test
public void testInsertBlob(){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JDBCTools.getConnection();
String sql = "INSERT INTO customers(name, email, birth, picture)"
+ "VALUES(?,?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "ABCDE");
preparedStatement.setString(2, "abcde@atguigu.com");
preparedStatement.setDate(3,
new Date(new java.util.Date().getTime()));
InputStream inputStream = new FileInputStream("Hydrangeas.jpg");
preparedStatement.setBlob(4, inputStream);
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally{
JDBCTools.releaseDB(null, preparedStatement, connection);
}
}
读取 blob 数据
/**
* 读取 blob 数据:
* 1. 使用 getBlob 方法读取到 Blob 对象
* 2. 调用 Blob 的 getBinaryStream() 方法得到输入流。再使用 IO 操作即可.
*/
@Test
public void readBlob(){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = JDBCTools.getConnection();
String sql = "SELECT id, name customerName, email, birth, picture "
+ "FROM customers WHERE id = 13";
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
String email = resultSet.getString(3);
System.out.println(id + ", " + name + ", " + email);
Blob picture = resultSet.getBlob(5);
InputStream in = picture.getBinaryStream();
System.out.println(in.available());
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);
}
in.close();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally{
JDBCTools.releaseDB(resultSet, preparedStatement, connection);
}
}