12:21 AM
0



Inserting a Picture(binary data) into Database

By using jdbc concepts we can store pictures into database. pictures means binary data.For storing binary data we have to use PreparedStatement interface.

PreparedStatement is an interface of java.sql.package and 
It  is extended from Statement interface.It is used to transfer charecter data and binary data along with sql commands into database.

Steps involved in storing pictures in database:

1.Establishing a Connection with database:

Class.forName("oracle.jdbc.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","username","password");

2.Create a PreparedStatement object:

PreparedStatement object will be created by calling prepareStatement() in Connection interface

PreparedStatement pstmt = con.prepareStatement(query);

3.Create File class object for image file and finding the length of image:

File file = new File(path);
int length = (int)file.length();

4.Create a FileInputStream object for corresponding file Object

FileInputStream fis = new FileInputStream(file);

5.Call setBinaryStream()

6.Call executeUpadate()

example:

program to store a image in database:


import java.sql.*;
import java.util.*;
import java.io.*;
class PictureInsert
{
public static void main(String args[])throws Exception
{
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("driver loaded");
Connection con =            DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println("connected to oracle");
PreparedStatement pstmt = con.prepareStatement("insert into profile values(?,?)");
Scanner s = new Scanner(System.in);
while(true)
{
System.out.println("enter company");
int pid = s.nextInt();
System.out.println("enter company logo");
String photo = s.next();

File file = new File(photo);
int length = (int)file.length();

FileInputStream fis = 
                        new   FileInputStream(file);

pstmt.setInt(1,pid);
pstmt.setBinaryStream(2,fis,length);
int i = pstmt.executeUpdate();
System.out.println(i+"rows inserted");
System.out.println("enter ur choice");
String choice = s.next();
if(choice.equals("y"))
{
}
else
break;
}
pstmt.close();
con.close();
}

}

Before compile this applicatation we have to create a table with name profile as follows:

create table profile(p_id  number(3),p_photo blob);

Here blob is a datatype which is used to store binary data.

0 comments:

Post a Comment