How to store image in Mysql Database in java

You should use BLOB data type for image filed.setBinaryStream() of PreparedStatement can be used  to set the stream to store images to the database.

Methods of PreparedStatement.

  • public void setBinaryStream(int paramIndex,InputStream stream)
    throws SQLException
  • public void setBinaryStream(int paramIndex,InputStream stream,long length)
    throws SQLException

Table structure for storing image.


CREATE TABLE  Product
(    name VARCHAR(40),
     image BLOB
)


package com.startwithjava;
import java.sql.*;
import java.io.*;
public class InsertImage {
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb","root","");

PreparedStatement ps=con.prepareStatement("insert into product values(?,?)");
ps.setString(1,"Product 1");

FileInputStream fin=new FileInputStream("d:\\1.jpg");
ps.setBinaryStream(2,fin,fin.available());
int i=ps.executeUpdate();
System.out.println(i+" records affected");
con.close();
}catch (Exception e) {e.printStackTrace();}
}
}

 

 

 

 

Leave a Reply