Javascript required
Skip to content Skip to sidebar Skip to footer

How to Insert Blob Data in Mysql Using Java

Summary: this tutorial shows you how to write and read MySQL BLOB data using JDBC API.

We will use the candidates table in the mysqljdbc sample database. For the sake of demonstration, we will add one more column named resume into the candidates table. The data type of this column will be MEDIUMBLOB that can hold up to 16MB.

The following ALTER TABLE statement adds resume column to the candidates table.

            

ALTER TABLE candidates ADD COLUMN resume LONGBLOB NULL AFTER email;

Code language: SQL (Structured Query Language) ( sql )

We will use a sample resume in PDF format and load this file into the resume column of the candidates table later. You can download the sample PDF file for practicing via the following link:

Download John Doe Resume in PDF format

Writing BLOB data into MySQL database

The steps for writing BLOB data into MySQL database is as follows:

First, open a new connection to the database by creating a new Connection object.

            

Connection conn = DriverManager.getConnection(url,username,password);

Code language: Java ( java )

Then, construct an UPDATE statement and create a PreparedStatement from the Connection object.

            

String updateSQL = "UPDATE candidates " + "SET resume = ? " + "WHERE id=?"; PreparedStatement pstmt = conn.prepareStatement(updateSQL);

Code language: Java ( java )

Next, read data from the sample resume file using FileInputStream and call setBinaryStream() method to set parameters for the PreparedStatement .

            

// read the file File file = new File(filename); FileInputStream input = new FileInputStream(file); // set parameters pstmt.setBinaryStream(1, input); pstmt.setInt(2, candidateId);

Code language: Java ( java )

After that, call the executeUpdate() method of the PreparedStatement object.

            

pstmt.executeUpdate();

Code language: Java ( java )

Finally, close the PreparedStatement and Connection objects by calling the close() methods.

To simplify the Connection creation process, we use the MySQLJDBCUtil class that we developed in the previous tutorial to open a new connection. The complete example of writing BLOB data into MySQL database is as follows:

            

package org.mysqltutorial; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * * @author mysqltutorial.org */ public class Main { /** * Update resume for a specific candidate * * @param candidateId * @param filename */ public static void writeBlob (int candidateId, String filename) { // update sql String updateSQL = "UPDATE candidates " + "SET resume = ? " + "WHERE id=?"; try (Connection conn = MySQLJDBCUtil.getConnection(); PreparedStatement pstmt = conn.prepareStatement(updateSQL)) { // read the file File file = new File(filename); FileInputStream input = new FileInputStream(file); // set parameters pstmt.setBinaryStream(1, input); pstmt.setInt(2, candidateId); // store the resume file in database System.out.println("Reading file " + file.getAbsolutePath()); System.out.println("Store file in the database."); pstmt.executeUpdate(); } catch (SQLException | FileNotFoundException e) { System.out.println(e.getMessage()); } } /** * @param args the command line arguments */ public static void main (String[] args) { writeBlob(122, "johndoe_resume.pdf"); } }

Code language: Java ( java )

Let's run the program.

mysql jdbc blob example

Now we check thecandidates table for the candidate with id 122.

            

SELECT * FROM candidates WHERE id = 122;

Code language: SQL (Structured Query Language) ( sql )
mysql jdbc insert blob example

As you see, we have BLOB data updated in the resume column of the candidates table for record with id 122.

Reading BLOB data from MySQL database

The process of reading BLOB data from the database is similar to the process of writing BLOB except for the part that we write BLOB data into the file.

First, open a new connection to the database.

            

Connection conn = MySQLJDBCUtil.getConnection(dbURL,username,password);

Code language: Java ( java )

Then, construct a SELECT statement and create a PreparedStatement from the Connection object.

            

String selectSQL = "SELECT resume FROM candidates WHERE id=?"; PreparedStatement pstmt = conn.prepareStatement(selectSQL);

Code language: Java ( java )

Next, set the parameters and execute the query:

            

pstmt.setInt(1, candidateId); ResultSet rs = pstmt.executeQuery();

Code language: Java ( java )

After that, get BLOB data from the ResultSet and write it into a file:

            

File file = new File(filename); FileOutputStream output = new FileOutputStream(file); System.out.println("Writing to file " + file.getAbsolutePath()); while (rs.next()) { InputStream input = rs.getBinaryStream("resume"); byte[] buffer = new byte[1024]; while (input.read(buffer) > 0) { output.write(buffer); } }

Code language: Java ( java )

Finally, call theclose() methods of PreparedStatment and Connection objects. If you use try-with-resources statement, you don't have to do it explicitly.

The following example illustrates how to read BLOB data from MySQL database.

            

package org.mysqltutorial; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author Main.org */ public class Main { /** * Read resume of a candidate and write it into a file * * @param candidateId * @param filename */ public static void readBlob (int candidateId, String filename) { // update sql String selectSQL = "SELECT resume FROM candidates WHERE id=?"; ResultSet rs = null; try (Connection conn = MySQLJDBCUtil.getConnection(); PreparedStatement pstmt = conn.prepareStatement(selectSQL);) { // set parameter; pstmt.setInt(1, candidateId); rs = pstmt.executeQuery(); // write binary stream into file File file = new File(filename); FileOutputStream output = new FileOutputStream(file); System.out.println("Writing to file " + file.getAbsolutePath()); while (rs.next()) { InputStream input = rs.getBinaryStream("resume"); byte[] buffer = new byte[1024]; while (input.read(buffer) > 0) { output.write(buffer); } } } catch (SQLException | IOException e) { System.out.println(e.getMessage()); } finally { try { if (rs != null) { rs.close(); } } catch (SQLException e) { System.out.println(e.getMessage()); } } } /** * @param args the command line arguments */ public static void main (String[] args) { // readBlob(122, "johndoe_resume_from_db.pdf"); } }

Code language: Java ( java )

After running the program, browsing the project the folder, you will see that there is a new file named johndoe_resume_from_db.pdf created.

mysql jdbc read blob example

In this tutorial, we have shown you how to work with MySQL BLOB data from JDBC.

Was this tutorial helpful?

How to Insert Blob Data in Mysql Using Java

Source: https://www.mysqltutorial.org/mysql-jdbc-blob