操作Blob类型字段
-
向数据表中插入Blob类型的字段 Blobl类型的字段是一个文件,文件的传输需要进行IO流操作 @Test
public void testBlob() {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JdbcUtils.getConnection();
String sql = "insert into customers(cust_name, cust_email, cust_birth,photo) values(?,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setObject(1, "生肖虎");
ps.setObject(2, "en@126.com");
ps.setObject(3, "2000-01-01");
File file = new File("C:\\Users\\NLC\\Desktop\\虎虎年画.jpg");
FileInputStream fis = new FileInputStream(file);
ps.setBlob(4,fis);
ps.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(conn,ps);
}
}
-
从数据表中读取Blob类型字段到本地 @Test
public void testBlobQuery() {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "select photo from customers where cust_name = ?";
ps = conn.prepareStatement(sql);
ps.setObject(1, "生肖虎");
rs = ps.executeQuery();
if (rs.next()) {
Blob blob = rs.getBlob("photo");
InputStream is = blob.getBinaryStream();
FileOutputStream fos = new FileOutputStream(new File("2022年画.jpg"));
int len = 0;
byte[] bytes = new byte[1024];
while ((len = is.read(bytes)) != -1) {
fos.write(bytes,0,len);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(conn,ps,rs);
}
}
-
关于 ”max_allowed_packet “ 的设置 3.1 传输大于4M的文件时,会有如下报错 3.2 在MySQL数据目录中的my.ini文件中进行配置 参考博文:MySQL5.7及以上版本的my.ini所在目录 3.3 重启MySQL服务
|