This example shows you how to read BLOBs data from database table.
package org.kodejava.jdbc;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
public class BlobReadDemo {
private static final String URL = "jdbc:mysql://localhost/kodejava";
private static final String USERNAME = "kodejava";
private static final String PASSWORD = "s3cr*t";
public static void main(String[] args) {
try (Connection conn =
DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
String sql = "SELECT name, image FROM product_image";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
File image = new File(name);
try (FileOutputStream fos = new FileOutputStream(image)) {
byte[] buffer = new byte[1024];
// Get the binary stream of our BLOB data
InputStream is = rs.getBinaryStream("image");
while (is.read(buffer) > 0) {
fos.write(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Table structure of product_image
CREATE TABLE `product_image`
(
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`product_id` bigint(20) unsigned NOT NULL,
`name` varchar(255) NOT NULL,
`description` varchar(255) DEFAULT NULL,
`image` blob,
PRIMARY KEY (`id`),
KEY `product_id` (`product_id`),
CONSTRAINT `product_image_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`)
) ENGINE = InnoDB;
Maven Dependencies
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024