Inserting Image in Database Table
In this section, you will learn to insert an image to the MySQL database table.
Flow of the process :
This program helps the user to insert an image in the MySQL database table. To insert an image, you need to establish a connection with MySQL database. Lets' take a database hibernatetutorial, in our case. This database has a table (Image table). For inserting an image in table, we have used the SQL statement ?INSERT INTO Image values(?,?,?)? with the prepareStatement() method. Whenever an image is inserted into the database, it displays ?Inserting Successfully?. If it fails to insert an image then it throws an exception.
[Note: The table has a specified field (or data type) to store an image of type e.g. Blob]
Here is the Code of Program :
import java.sql.*; import java.io.*; public class insertImage{ public static void main(String[] args) { System.out.println("Insert Image Example!"); String driverName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/"; String dbName = "hibernatetutorial"; String userName = "root"; String password = "root"; Connection con = null; try{ Class.forName(driverName); con = DriverManager.getConnection(url+dbName,userName,password); Statement st = con.createStatement(); File imgfile = new File("images.jpg"); FileInputStream fin = new FileInputStream(imgfile); PreparedStatement pre = con.prepareStatement("insert into Image values(?,?,?)"); pre.setInt(1,5); pre.setString(2,"Durga"); pre.setBinaryStream(3,fin,(int)imgfile.length()); pre.executeUpdate(); System.out.println("Inserting Successfully!"); pre.close(); con.close(); } catch (Exception e){ System.out.println(e.getMessage()); } } }
Output of this Program:
C:\Roseindia\vinod\jdbc4.0>javac
insertImage.java C:\Roseindia\vinod\jdbc4.0>java insertImage Insert Image Example! Inserting Successfully! C:\Roseindia\vinod\jdbc4.0> |
Table Name: Image
![]() |
Durga.jpg
![]() |