Enjoyed this tutorial?
Subscribe to Ram N Java for regular, beginner-friendly Java & database tutorials!
▶ Subscribe NowIntroduction
Storing multimedia files like images, audio, or PDFs inside a relational database is a standard requirement for many Java applications. In relational databases like MySQL, binary files are stored using the BLOB (Binary Large Object) data type.
With Java Database Connectivity (JDBC), you can read an image file from your local storage, convert it into an input stream, and save it directly into a MySQL table using a PreparedStatement.
Database Table Structure
Before executing the Java code, create a dedicated table named city_image with a BLOB column to hold the image bytes:
CREATE TABLE city_image (
id INT PRIMARY KEY,
name VARCHAR(100),
photo BLOB
);
Step-by-Step Implementation in Java
- Load the JDBC Driver: Register the MySQL JDBC driver class using
Class.forName("com.mysql.cj.jdbc.Driver"). - Establish Connection: Connect to MySQL using
DriverManager.getConnection()with your database URL, username, and password. - Prepare the SQL Query: Create a parameterized query such as
INSERT INTO city_image (id, name, photo) VALUES (?, ?, ?). - Read the File into a Stream: Wrap your local image file using
FileInputStream. - Set Binary Stream: Use the
setBinaryStream()method ofPreparedStatementto pass the stream to the BLOB column. - Execute and Clean Up: Call
executeUpdate()to save the record, and close all resources in afinallyblock.
Understanding setBinaryStream()
The PreparedStatement interface provides overloaded versions of the setBinaryStream() method:
setBinaryStream(int parameterIndex, InputStream x)setBinaryStream(int parameterIndex, InputStream x, long length)
This method streams the raw binary contents directly from your disk to the database server without loading the entire file into memory as a giant byte array.
Recommended Related Tutorials
Continue mastering Java Database Connectivity with these practical guides:
Click here to watch in Youtube : https://www.youtube.com/watch?v=GCzdfiia_LU
Click the below Image to Enlarge
![]() |
| JDBC : Store Image |
![]() |
| JDBC : Store Image |
![]() |
| JDBC : Store Image |
![]() |
| JDBC : Store Image |
![]() |
| JDBC : Store Image |





No comments:
Post a Comment