Database BLOBs (Binary Large Objects) can be used to store any data, such as images, audio, or video files, for instance. This example shows you how we use JDBC library to store image in our database. To send the binary information to the database, we can call the PreparedStatement.setBinaryStream()
method and pass the appropriate input stream and its size.
package org.kodejava.jdbc;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class BlobDemo {
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)) {
conn.setAutoCommit(false);
String sql = "INSERT INTO product_image " +
"(product_id, name, description, image) VALUES (?, ?, ?, ?)";
String image = "/uml-distilled-3rd-edition.jpg";
try (PreparedStatement stmt = conn.prepareStatement(sql);
InputStream is = BlobDemo.class.getResourceAsStream(image)) {
stmt.setLong(1, 1L);
stmt.setString(2, "uml-distilled-3rd-edition.jpg");
stmt.setString(3, "UML Distilled 3rd Edition");
stmt.setBinaryStream(4, is);
stmt.execute();
conn.commit();
} catch (Exception e) {
conn.rollback();
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The structure of product_image
table.
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
Try update
stmt.execute();
tostmt.executeUpdate();
🙂Follow: Insert picture to MySQL : Blob