上传图片
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进行的预处理
本文详细介绍了使用Java和MySQL数据库进行图片数据的存储与读取过程。通过PreparedStatement预处理语句,实现图片文件的二进制流上传至数据库,并演示了如何从数据库中检索图片数据并保存到本地。
338

被折叠的 条评论
为什么被折叠?



