🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Table of Contents
- Introduction
- Setting Up the MySQL Database
- JDBC Driver and Dependencies
- Inserting Images into MySQL Database
- Retrieving Images from MySQL Database
- Example Code
- Conclusion
1. Introduction
Storing images in a database can be a useful feature for many applications. This tutorial will guide you through the process of inserting and retrieving images from a MySQL database using Java JDBC.
2. Setting Up the MySQL Database
First, ensure that MySQL is installed and running. Create a new database and table for this example.
CREATE DATABASE test_db;
USE test_db;
CREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
image LONGBLOB NOT NULL
);
3. JDBC Driver and Dependencies
To connect to MySQL from Java, you need the MySQL JDBC driver. You can download it from the MySQL website. Add the downloaded JAR file to your project's build path.
If you are using Maven, add the following dependency to your pom.xml:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
4. Inserting Images into MySQL Database
To insert an image into the database, you need to read the image file into a byte array and then use a PreparedStatement to insert it into the database.
Insert Image Example
package com.example.jdbc;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class InsertImageExample {
private static final String URL = "jdbc:mysql://localhost:3306/test_db?useSSL=false";
private static final String USER = "root";
private static final String PASSWORD = "root";
private static final String INSERT_IMAGE_SQL = "INSERT INTO images (name, image) VALUES (?, ?);";
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_IMAGE_SQL);
preparedStatement.setString(1, "Sample Image");
// Read the image file and set it as a binary stream
try (FileInputStream inputStream = new FileInputStream("path/to/your/image.jpg")) {
preparedStatement.setBinaryStream(2, inputStream, inputStream.available());
preparedStatement.executeUpdate();
System.out.println("Image inserted successfully!");
} catch (IOException e) {
e.printStackTrace();
}
} catch (SQLException e) {
printSQLException(e);
}
}
public static void printSQLException(SQLException ex) {
for (Throwable e : ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}
5. Retrieving Images from MySQL Database
To retrieve an image from the database, you need to use a PreparedStatement to query the image and then read the binary data from the ResultSet.
Retrieve Image Example
package com.example.jdbc;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class RetrieveImageExample {
private static final String URL = "jdbc:mysql://localhost:3306/test_db?useSSL=false";
private static final String USER = "root";
private static final String PASSWORD = "root";
private static final String SELECT_IMAGE_SQL = "SELECT name, image FROM images WHERE id = ?;";
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
PreparedStatement preparedStatement = connection.prepareStatement(SELECT_IMAGE_SQL);
preparedStatement.setInt(1, 1); // Assume we are retrieving the image with ID 1
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
String name = resultSet.getString("name");
InputStream inputStream = resultSet.getBinaryStream("image");
// Save the image to a file
try (FileOutputStream outputStream = new FileOutputStream("output_image.jpg")) {
byte[] buffer = new byte[1024];
while (inputStream.read(buffer) > 0) {
outputStream.write(buffer);
}
System.out.println("Image retrieved and saved as 'output_image.jpg'!");
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
printSQLException(e);
}
}
public static void printSQLException(SQLException ex) {
for (Throwable e : ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}
6. Conclusion
Inserting and retrieving images from a MySQL database using Java JDBC is a straightforward process. By using PreparedStatement for insertion and retrieval, you can handle binary data efficiently. This tutorial covered setting up the MySQL database, inserting an image, and retrieving it back to a file. Using these techniques, you can manage image data in your Java applications effectively.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment