Reading and writing blob from the oracle database.
Hi all,
I am using Oracle 8.1.5 on WinNT. I have written a code for inserting a file in the table which has a column defined as blob. I have classes111.zip in the classpath. Following are the important snippets from the code:
......
static final String driver_class = "oracle.jdbc.driver.OracleDriver";
static final String connect_string = "jdbc:oracle:thin:scott/tiger@ibm-hard:1521:orabt";
....
Class.forName (driver_class);
conn = DriverManager.getConnection (connect_string);
conn.setAutoCommit(false);
....
String sqlStmt = "INSERT INTO TEST_BLOB VALUES ('object1', empty_blob())";
stat = conn.createStatement();
stat.executeQuery(sqlStmt);
String updateSQL = "select report_doc from test_blob where report_name='object1' for update";
rs = stat.executeQuery(updateSQL);
rs.next();
BLOB blob = ((OracleResultSet)rs).getBLOB("report_doc");
OutputStream os = blob.getBinaryOutputStream();
File f = new File("D:\\Project\\molsa\\social_schema.txt");
InputStream is = new FileInputStream(f);
int fileLength = (int)f.length();
final byte[] buffer = new byte[(int)fileLength];
System.out.println("File length is " + fileLength);
int bytesRead = 0;
int totalBytesRead = 0;
while((bytesRead = is.read(buffer)) != -1) {
totalBytesRead += bytesRead;
System.out.println(totalBytesRead);
os.write(buffer, 0, bytesRead);
}
...........
When I run this program everything seems to have run fine. But when I am trying to read the same blob using the following code:
------------------------------------------------------------------
String getDocSQL = "select * from test_blob";
stat = conn.createStatement();
rs = stat.executeQuery(getDocSQL);
while(rs.next()) {
BLOB blobData = ((OracleResultSet)rs).getBLOB("report_doc");
InputStream is = blobData.getBinaryStream();
FileOutputStream fos = new FileOutputStream(new File("D:\\Project\\molsa\\social_schema1.txt"));
int totalBytesRead = 0;
final int bufferSize = (int) blobData.length();
byte[] buffer = new byte[bufferSize];
System.out.println("Length of data " + bufferSize);
int bytesRead = 0;
while ((bytesRead = is.read(buffer, 0, bufferSize)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
------------------------------------------------------------------
I am having two problems:
1. the size of the file is shown as a bit less than that of the file which I wrote initially.
2. and I am getting an exception
java.io.IOException: ORA-21560: argument 2 is null, invalid, or out of range
ORA-06512: at "SYS.DBMS_LOB", line 640
ORA-06512: at line 1
at oracle.jdbc.dbaccess.DBError.SQLToIOException(DBError.java:774)
at oracle.jdbc.driver.OracleBlobInputStream.needBytes(OracleBlobInputStream.java:141)
at oracle.jdbc.driver.OracleBufferedStream.read(OracleBufferedStream.java:107)
at ThinClient.main(ThinClient.java:83)
Thanks in advance
Vivek Singh