上传图片
public void GetConnectionTest() throws SQLException, FileNotFoundException {
//定义url
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT";
//创建Driver驱动
Driver driver = new com.mysql.cj.jdbc.Driver();
//通过驱动获取链接
Properties pro = new Properties();
pro.setProperty("user", "root");
pro.setProperty("password", "123456");
Connection conn = driver.connect(url, pro);
String sql = "insert into test1 (t_id,t_image) value (?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
InputStream in = new FileInputStream(new File("src/123.jpg"));
pstmt.setBlob(2, in);
//执行
pstmt.executeUpdate();
//释放资源
JDBCUtil.releaseSource(null, pstmt, conn);
}
读取
public void queryBlob() throws SQLException, IOException {
//定义url
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT";
//创建Driver驱动
Driver driver = new com.mysql.cj.jdbc.Driver();
//通过驱动获取链接
Properties pro = new Properties();
pro.setProperty("user", "root");
pro.setProperty("password", "123456");
Connection conn = driver.connect(url, pro);
String sql = "select t_image from test1 where t_id=?";
//获取执行对象
PreparedStatement pstmt = conn.prepareStatement(sql);
//设置参数
pstmt.setInt(1, 1);
//执行sql
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
Blob photo = rs.getBlob("t_image");
InputStream in = photo.getBinaryStream();
OutputStream out = new FileOutputStream(new File("src/1233.jpg"));
byte[] buf = new byte[1024];
int len =0;
while((len = in.read(buf))!= -1) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
//释放资源
JDBCUtil.releaseSource(rs, pstmt, conn);
}
注:此处用的是PreparedStatement进行的预处理