`

Save/Write/Read image from/to a database table

 
阅读更多

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();

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics