前言
将二进制文件插入MySQL数据库,一些重要的文件可以插入,其实一些不太重要的可以存入文件,然后数据库存它在服务器上的路径。
一、Blob
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服务。
2、写Blob数据
/**
* @function 插入blob
*/
@Test
public void updateBlob() {
String sql = "update customers set photo = ? where id = ?";
try (Connection conn = getConn();
PreparedStatement ps = conn.prepareStatement(sql);
FileInputStream is = new FileInputStream("壁纸.mp4");) {
ps.setObject(1, is);
ps.setObject(2, 19);
ps.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
3、读Blob数据
/**
* @function 从数据库把二进制文件读出来
*/
@Test
public void getBlob() {
String sql = "select id,name,email,birth,photo from customers where id = ?";
InputStream is = null;
OutputStream os = null;
try (Connection conn = getConn();
PreparedStatement ps = conn.prepareStatement(sql);
) {
ps.setObject(1, 19);
ResultSet res = ps.executeQuery();
if (res.next()) {
int id = res.getInt("id");
String name = res.getString("name");
String email = res.getString("email");
Blob photo = res.getBlob("photo");
is = new BufferedInputStream(photo.getBinaryStream());
os = new BufferedOutputStream(new FileOutputStream("blob.mp4"));
int n = 0;
while ((n = is.read()) != -1) {
os.write(n);
}
os.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
总结
1)如何插入二进制文件到MySQL中。
参考文献
[1] JDBC 尚硅谷