In most cases, the blob type is used to store an image in a MySQL database. Therefore, ensure that a table with a blob datatype has been created and has the following description:
+——-+————–+——+—–+———+——-+
| Field | Type | Null | Key | Default | Extra |
+——-+————–+——+—–+———+——-+
| Name | varchar(255) | YES | | NULL | |
| image | blob | YES | | NULL | |
+——-+————–+——+—–+———+——-+
To insert an image in to MySQL database, follow the steps given below:
Step 1: Connect to the database
The DriverManager class’s getConnection() method lets you establish a database connection.
Pass the login, password, and MySQL URL, which is jdbc:mysql:/localhost/sampleDB (where sampleDB is the database name), as inputs to the getConnection() method to establish a connection to the MySQL database.
String mysqlUrl = “jdbc:mysql://localhost/hitech”;
Connection con = DriverManager.getConnection(mysqlUrl, “root”, “password”);
Step 2: Create a Prepared statement
Create a PreparedStatement object using the prepareStatement() method of the Connection interface. To this method pass the insert query (with place holders) as a parameter
PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?, ?)");
Step 3: Set values to the place holder
Utilizing the PreparedStatement interface's setter methods, set the values for the placeholders. choose the methods based on the column's data type. Use the setString() method, for instance, if the column is of type VARCHAR, and the setInt() method if it is of type INT.
Additionally, you can set a value to it using the setBinaryStream() or setBlob() methods if it is of the Blob type. Pass an object of the InputStream class and an integer variable indicating the parameter index to these methods as parameters.
pstmt.setString(1, "sample image"); //Inserting Blob type InputStream in = new FileInputStream("E:\images\cat.jpg"); pstmt.setBlob(2, in);
Step 4: Execute the statement
Execute the above created PreparedStatement object using the execute() method of the PreparedStatement interface.
Example
import java.io.FileInputStream; import java.io.InputStream import java.sql.Connection import java.sql.DriverManager; import java.sql.PreparedStatement; public class InsertImageToMySqlDB { public static void main(String args[]) throws Exception{ //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()) //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/hitech"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?,?)"); pstmt.setString(1, "sample image"); //Inserting Blob type InputStream in = new FileInputStream("E:\images\cat.jpg"); pstmt.setBlob(2, in); //Executing the statement pstmt.execute(); System.out.println("Record inserted......"); }
Output
Connection established……
Record inserted……