• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

converting inputstream to BLOB

 
saravana kumar
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

i want to store bytes into database. the type in database is BLOB. now i have a fileoutputstream which contains data. i want to store into database. how to do this in java? can anyone have sample code for this ?

pls help me to solce this problem.

Thanks & regards
saran
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35269
383
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Saran,
You can wrap that stream in a BinaryStream and use preparedStatement.setBinaryStream() to write to the BLOB.
 
tommy k. lee
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What database are you using? For instance, if you are using Oracle, there are special API's (i.e. non-standard JDBC) in the drivers that can be used to persist BLOB data.

For Oracle Databases:
-----------------------
First you need a reference to the BLOB. Then you write the data to the BLOB, which buffers it. Finally, you update the BLOB column with the modified BLOB, like this:

//Use oracle.sql.BLOB because java.sql.Blob lacks setBytes()
//JDBC3 java.sql.Blob adds the method setBytes(int,byte[])
//Oracle JDBC uses the method putBytes(int,byte[])
oracle.sql.BLOB dbBlob = (oracle.sql.BLOB)rs.getBlob(1);
//update blob
ps = cxn.prepareStatement(sqlSetBlob);
ps.setString(2,SomeValue);
dbBlob.putBytes(1,blob.getRaw());
/*
You can't do this:
ps.setBinaryStream(1,blob.getInputStream(),blob.getRaw().length);
You must do it like this:
ps.setBlob(1,dbBlob);
Which is weird because you CAN do this:
InputStream is = rs.getBinaryStream(1);
Note that if the column were declared LONGVARBINARY then
setBinaryStream() would work.
*/
ps.setBlob(1,dbBlob);
cxn.commit();
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic