Writing-Reading Images (using BLOB)

Some programmers prefer to put images into the database, some prefer to them on the file system for their applications. Images are binary data. MySQL database has a special data type to store binary data called BLOB (Binary Large Object)
The BLOB Data Types
Images are made up of binary data so this data cannot be stored in normal text fields in MySQL/Oracle (such as text or varchar). Instead, we must use the blob type.
The four types of BLOBs in My-Sql are as follows: -
TYPE Size (Approx.)
Tinyblob 255 Bytes
Blob 65 KB
Mediumblob 16 MB
Longblob 4 GB
The actual type you choose doesn't really matter, since it only stores as such data as you need. Therefore the longlob type is recommend to use.
Writing Image in Database Table
The following programs demonstrates how to write an image file in database table using longblob type.
First create a table named PICS in your database. The table should have a fileld named: PIC having type: longblob.
Current directory must have a .jpg file to write in database otherwise the program throws FileNotFoundException.
import java.io.*;
import java.sql.*;
public class WriteImage 
    public static void main(String[] args) 
        Connection con = null;
        PreparedStatement pst = null;
        FileInputStream fin = null;
        String cs = "jdbc:mysql://localhost:3306/college";
        String user = "root";
        String password = "urMySqlPassword";                 
        try {
            File img = new File("urPicName.jpg");
            fin = new FileInputStream(img);
            con = DriverManager.getConnection(cs, user, password);
            pst = con.prepareStatement("INSERT INTO PICS VALUES(?)");
            pst.setBinaryStream(1, fin, (int) img.length());
            System.out.println("Pic Stored in Database Table...");
        catch (Exception ex) { ex.printStackTrace(); }

In line number:14, the file to be written is referenced by the file class object; then it is chained to FileInputStream Class object(fin);using setbinarystream() and executeupdate() methods of prepared statement the image file it is sent to database table.

About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
20 Years experience in Training & Development. Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android,MERN Stack(MongoDB,Express,ReactJS,NodeJS). If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : bcebti@gmail.com #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "realJavaOnline.com". M:9872246056
Card image cap