Wednesday, July 1, 2009

Storing Images into Database using JDBC

We can store images into database using BLOB data type and also managing SQL 92 data types (BLOB, CLOB and Ref)

BLOB (Binary Large OBject)

  • Used to store binary informations like images, audio files etc
  • For each byte one byte of memory will be allocated
  • Size can vary up to 4GB for each entry
CLOB (Character LOB)
  • Used to store character information like plain, word documents
  • For each character two bytes of memory is allocated
  • Size up to 4GB
StoreImage.java
import java.sql.*;
import java.io.*;

public class StoreImage
{
public static void main(String rags[]) throws Exception

{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con=DriverManager.getConnection("jdbc:odbc:yourdsn","scott", "tiger");
PreparedStatement pstmt=con.prepareStatement
("insert into ImgStore values(?,?)");

File f=new File("pic.jpg");
FileInputStream fis=new FileInputStream(f);

pstmt.setInt(1, 1);
pstmt.setBinaryStream(2, fis, (int)f.length());
int i=pstmt.executeUpdate();
System.out.println(i+" record inserted");
pstmt.close();
con.close();
}
}
sqlplus scott/tiger
cle scr
--create table ImgStore (id number, image BLOB);

ImageRestore.java
import java.io.*;
import java.sql.*;

public class RestoreImage
{
public static void main(String rags[]) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con=DriverManager.getConnection("jdbc:odbc:yourdsn","scott", "tiger");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from temp");
if(rs.next())
{
System.out.println(rs.getInt(1));
InputStream in=rs.getBinaryStream(2);

FileOutputStream fos=new FileOutputStream("pic1.jpg");
int i=in.read();
while(i!=-1)
{
fos.write(i);
i=in.read();
}
fos.close();
in.close();
}
rs.close();

stmt.close();
con.close();
}
}

1 comments:

Guest,  July 24, 2009 at 2:13 AM  

Hi,

are you interested in link exchange with my blog www.itdiligent.com

if you are interested please mail me admin@itdiligent.com

Regards
Admin@itdiligent.com

Blog Widget by LinkWithin

JS-Kit Comments

  © Blogger template Newspaper III by Ourblogtemplates.com 2008

Back to TOP