java图片怎么写入与读出数据库
时间: 2023-06-10 17:05:28 浏览: 53
Java中可以使用Blob类来实现图片的读写操作。下面是一个简单的代码示例:
// 写入图片到数据库
public void writeImageToDatabase(Connection conn, String name, String filePath) throws SQLException, IOException {
PreparedStatement pst = conn.prepareStatement("INSERT INTO images (name, image) VALUES (?, ?)");
pst.setString(1, name);
pst.setBlob(2, new FileInputStream(filePath));
pst.executeUpdate();
pst.close();
}
// 读取图片从数据库
public void readImageFromDatabase(Connection conn, String name, String filePath) throws SQLException, IOException {
PreparedStatement pst = conn.prepareStatement("SELECT image FROM images WHERE name = ?");
pst.setString(1, name);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
Blob blob = rs.getBlob("image");
InputStream is = blob.getBinaryStream();
FileOutputStream fos = new FileOutputStream(filePath);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
}
rs.close();
pst.close();
}
如果您需要更详细的解释,请告诉我。