Writing and Reading MySQL BLOB Using JDBC?
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.
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: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.
Then, construct an UPDATE statement and create a
PreparedStatement
from the Connection
object.
Next, read data from the sample resume file using
FileInputStream
and call setBinaryStream()
method to set parameters for the PreparedStatement
.
After that, call the
executeUpdate()
method of the PreparedStatement
object.
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:
Let’s run the program.
Now we check the
candidates
table for the candidate with id 122.
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.
Then, construct a SELECT statement and create a
PreparedStatement
from the Connection
object.
Next, set the parameters and execute the query:
After that, get BLOB data from the
ResultSet
and write it into a file:
Finally, call the
close()
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.
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.
In this tutorial, we have shown you how to work with MySQL BLOB data from JDBC.
0 comments:
Post a Comment