Storing image into database.

We can store image into database using blob field type. here is a simple example that will read image file and store it to database.

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 = "mydatabase";
        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,"Hemraj");
            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());
        }
    }
}
Image file will be stored into database and cab be retried latter as a binary stream that can be converted into image file using IO utilities. 

No comments:

Popular Posts