Useful Tips : How to insert BLOB into an Oracle database using JDBC
It can be quite disturbing to try to insert a BLOB (Binary Large OBject) using JDBC, because most of the time java softwares will handle BLOB, not exactly using their own time, but using Strings.
And if you try let's say this kind of query :
// blob String :
String blobToInsert = ....;
StringBuilder insertQuery = new StringBuilder();
insertQuery.append("insert into ");
insertQuery.append(" table( table_id, table_blob_field ) ");
insertQuery.append("values ");
insertQuery.append(" ('64', '" + blobToInsert + "' )");
And try to execute it,you will end up having several different kind of errors, once Oracle may tell you that the field is too long, to finally end up telling you a strange type error.
The trick is the following, you can't use Strings (or StringBuilder/StringBuffer/etc... ) because it won't define the type of Object you'll be using. So you'll have to use a prepare statement (normally used for optimization when you're using more than once a query) this way :
// blob String :
String blobToInsert = ....;
StringBuilder insertQuery = new StringBuilder();
insertQuery.append("insert into ");
insertQuery.append(" table( table_id, table_blob_field ) ");
insertQuery.append("values ");
insertQuery.append(" ('64', ? )");
PrepareStatement psInsert = con.prepareStatement(insertQuery.toString());
// and then set :
psInsert.setBytes(1, blobToInsert.getBytes());
// and execute the query :
psInsert.execute();
This way you won't be bothered, because nowadays JDBC connection using Oracle drivers can recognize BLOBs and do the work for you.
Enjoy.
Newsletter
Stay updated with new articles.
Keep reading
Useful tips : Insert a clob of more than 4k into database
In fact clob are designed to be large objects consisting of characters, so you might be surprise if you try once, with Java JDBC to insert into a database a String of more than 4000 chars... Because t...
Jun 25, 2009
Useful Tips : StringBuilder and Java String Concatenation
As you certainly now, string concatenation in Java can be achieved using the "+" operator like that : ``` String parText = "This " + "is " + "a full text"; parText = parText + " in a new String objec...
Nov 14, 2009Useful Tips : How to create a thread that must get a result with a timeout time
Many times threads are really useful to use, but most of the time you don't want an asynchronous thread to run forever... Especially when you want it to execute tasks or fetch some data from a servlet...
Jun 9, 2009
No comments yet. Be the first to comment!