MySQL BLOB类型:

  • MySQL中,BLOB是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。
  • 插入BLOB类型的数据必须使用PrepareStatement,因为BLOB类型的数据无法使用字符串拼写。
  • MySQL的四种BLOB类型(除了在存储的最大信息量上不同外,他们是等同的)

  • 实际使用中根据需要存入的数据大小定义不同的Blob类型。
  • 需要注意的是:如果存储的文件过大,数据库的性能会下降。
  • 如果在指定了相关的Blob类型以后,还报错:xxx too large,那么在mysql的安装目录下,找my.ini文件加上如下的配置参数:max_allowed_packet=16M。同时注意:修改了my.ini文件之后,需要重新启动Mysql服务。

向数据表中插入大数据类型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 获取连接
Connection conn = JDBCUtils.getConnection();

// sql插入语句,值用占位符替代
String sql = "insert into customer(name,emial,birth,photo)values(?,?,?,?)";
PreparedStatement ps = conn.prepareStaement(sql);

// 填充占位符
ps.setString(1,"路飞");
ps.setString(2,"Cy7heng@163.com");
ps.setData(3,new Data(new java.util.Data.getTime()));
//操作Bolb类型的变量
FileInputStream fis = new FileInputStream("Suolong.PNG");
ps.setBlob(4,fis);

//执行
ps.execute();
//关闭
fis.close();
JDBCUtils.CloseResource(conn,ps);

修改数据表中的Blob类型字段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 获取连接
Connection conn = JDBCUtils.getConnection();

// sql更新语句,值用占位符替代
String sql = "update customer set photo = ? where id = ?";
PreparedStatement ps = conn.prepareStatement(sql);

// 填充占位符
// 操作Blob类型的变量
FileInputStream fis = new FileInputStream("luobin.png");
ps.setBlob(1,fis);
ps.setInt(2,25);

// 执行
ps.execute();
// 关闭
fis.close();
JDBCUtils.closeResource(conn,ps);

从数据表读取大量数据类型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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 bytr[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();
}
}