∟Retrieving BLOB Values with getBinaryStream() Method
This section describes how to retrieve BLOB values with the ResultSet.getBinaryStream() method.
BLOB values can also be retrieved with the getBinaryStream() method on the ResultSet object, which will return an OutputStream object.
Then you can read the BLOB values from the OutputStream object with the read() method.
The sample program below shows you how to create OutputStream objects with the getBinaryStream() method. A utility method is included
to read all bytes from an OutputStream object and save them in a file.
/**
* MySqlBlobGetBinaryStream.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.io.*;
import java.sql.*;
public class MySqlBlobGetBinaryStream {
public static void main(String [] args) {
Connection con = null;
try {
com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds
= new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
ds.setServerName("localhost");
ds.setPortNumber(3306);
ds.setDatabaseName("HerongDB");
ds.setUser("Herong");
ds.setPassword("TopSecret");
con = ds.getConnection();
// Retrieving CLOB value with getBinaryStream()
Statement sta = con.createStatement();
ResultSet res = sta.executeQuery("SELECT * FROM Image");
int i = 0;
while (res.next() && i<3) {
i++;
System.out.println("Record ID: "+res.getInt("ID"));
System.out.println(" Subject = "+res.getString("Subject"));
InputStream bodyOut = res.getBinaryStream("Body");
String fileOut = "BlobOut_"+res.getInt("ID")+".bin";
saveOutputStream(fileOut,bodyOut);
bodyOut.close();
System.out.println(" Body = (Saved in "+fileOut+")");
}
res.close();
sta.close();
con.close();
} catch (Exception e) {
System.err.println("Exception: "+e.getMessage());
e.printStackTrace();
}
}
public static void saveOutputStream(String name, InputStream body) {
int c;
try {
OutputStream f = new FileOutputStream(name);
while ((c=body.read())>-1) {
f.write(c);
}
f.close();
} catch (Exception e) {
System.err.println("Exception: "+e.getMessage());
e.printStackTrace();
}
}
}
The output looked correct:
C:\>java -cp .;\local\lib\mysql-connector-java-5.0.7-bin.jar
MySqlBlobGetBinaryStream
Record ID: 4
Subject = Test on INSERT statement
Body = (Saved in BlobOut_4.bin)
Record ID: 10
Subject = Test of the setBytes() method
Body = (Saved in BlobOut_10.bin)
Record ID: 15
Subject = Test of setBinaryStream() methods
Body = (Saved in BlobOut_15.bin)
I also tested BlobOut_15.bin file to make sure that I am getting my MySqlBlobSetBinaryStream.class file back correctly:
C:\>del MySqlBlobSetBinaryStream.class
C:\>copy BlobOut_15.bin MySqlBlobSetBinaryStream.class
1 file(s) copied.
C:\>java -cp .;\local\lib\mysql-connector-java-5.0.7-bin.jar
MySqlBlobSetBinaryStream
The inserted record:
Subject = Test of setBinaryStream() methods
Body = -||+ 2 |
...