Insert images in database


Prev Tutorial Next Tutorial

Insert images in database

you can not Insert a picture in database directly. but you can store binary data of picture file. To insert image in database we need a column of type BLOB (Binary Large Object).

insert image in databse

Important Points

  • In Jdbc only PreparedStatement support the binary data transfer between a Java application to database.
  • Jdbc supports only gif or jpeg or png type of images to insert or read from a database.
  • To set binary data into a parameter of PreparedStatement object, you need to call setBinaryStream().

Parameters of setBinaryStream()

  • parameter index
  • fileInputStream object
  • Size of the file

Find size of Image

To find the size of an image file we need File class object for that file.

Example

File f=new File("c:/img001.gif");
int size=(int)f.length();

Note: In Java forward slash (/) is allowed but backward slash (\) is not allowed at the time of writing of path.

Example to Insert Image in database

import java.sql.*;
import java.util.*;
import java.io.*;
class PhotoInsert 
{
Connection con;
public void openCon()throws Exception
{
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@rama-pc:1521:xe","system","system");
System.out.println("connection is opened");
}
public void insert()throws Exception
{
Scanner s=new Scanner(System.in);
PreparedStatement pstmt=con.prepareStatement("insert into emp_info values(?,?,?)");
System.out.println("enter emp id");
int empid=s.nextInt();
pstmt.setInt(1,empid);
System.out.println("enter emp name");
String empname=s.next();
pstmt.setString(2,empname);
System.out.println("enter photo file path");
String path=s.next();

File f=new File("c:/pho001.gif");
int size=(int) f.length();
FileInputStream fis=new FileInputStream(f);
pstmt.setBinaryStream(3,fis,size);
int i=pstmt.executeUpdate();
System.out.println(i+"row inserted");
pstmt.close();
fis.close();
}
public void closeCon()throws Exception
{
con.close();
}

public static void main(String[] args)throws Exception 
{
 PhotoInsert p1= new PhotoInsert();
 p1.openCon();
 p1.insert();
 p1.closeCon();
 }
}

Prev Tutorial Next Tutorial

Advertisements




Facebook Likes

Advertisements