How do you save and load an image from a database and display it in Java? I can get the file location, but I am unsure as to how to save it as a blob in the database or display the image in a swing window. I am using a PreparedStatement
to get information in and out of the database.
See this MySQL Java tutorial for examples under the sections Writing images and Reading images . In outline,
// writing
String sql = "INSERT INTO Images(Data) VALUES(?)";
PreparedStatement pst = con.prepareStatement(sql);
FileInputStream fin = new FileInputStream(myFile);
pst.setBinaryStream(1, fin, (int) myFile.length());
pst.executeUpdate();
//reading
String query = "SELECT Data FROM Images LIMIT 1";
PreparedStatement pst = con.prepareStatement(query);
ResultSet result = pst.executeQuery();
result.next();
String fileName = "src/main/resources/tree.png";
FileOutputStream fos = new FileOutputStream(fileName);
Blob blob = result.getBlob("Data");
int len = (int) blob.length();
byte[] buf = blob.getBytes(1, len);
fos.write(buf, 0, len);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.