Wednesday, 9 May 2012

Save/Write/Read image file from/to a database using Java program

Assuming you have a table with a blob field and you want to save a file and store it in the database table or you want to read from a blob object stored in a database, you can use these below java code snippets to write file and read file from database.

The sample table is created as below to have a blob field to store file.

CREATE TABLE t1 (c1 INT PRIMARY KEY NOT NULL, c2 BLOB(5M));
Then use the below code snippet to insert an image file as follows.



PreparedStatement pstmt = conn.prepareStatement ("INSERT INTO t1 VALUES (?,?)");
pstmt.setInt (1, 100);
File fBlob = new File ( "image1.gif" );
FileInputStream is = new FileInputStream ( fBlob );
pstmt.setBinaryStream (2, is, (int) fBlob.length() );
pstmt.execute ();
...


Retrieving a BLOB or in other words retrieving the image file stored in the database as follows:


Statement stmt = conn.createStatement ();
ResultSet rs= stmt.executeQuery("SELECT * FROM t1");
while(rs.next()) {
int val1 = rs.getInt(1);
InputStream val2 = rs.getBinaryStream(2);
...
} rs.close();

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...