下面列出了java.sql.ResultSet#getBinaryStream ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
*
* @param Id
* @param Ver
* @return
* @throws PDException
*/
protected InputStream Retrieve(String Id, String Ver, Record Rec) throws PDException
{
VerifyId(Id);
try {
String SQL = "SELECT PDCONT FROM "+getTable()+" where PDId='"+Id+"' and PDVersion='"+Ver+"'";
PreparedStatement BlobStmt = con.prepareStatement(SQL);
ResultSet resultSet = BlobStmt.executeQuery();
while (resultSet.next())
{
return (resultSet.getBinaryStream(1));
}
PDException.GenPDException("Inexistent_content", Id+"/"+Ver);
} catch (Exception ex)
{
PDException.GenPDException("Error_retrieving_content", ex.getLocalizedMessage());
}
return(null);
}
public byte[] getBytes() {
try {
final DataSource ds = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/DefaultDatabase");
final Connection c = ds.getConnection();
final PreparedStatement ps = c.prepareStatement("SELECT blob_column FROM storage WHERE id = ?");
ps.setInt(1, (Integer) ctx.getPrimaryKey());
final ResultSet rs = ps.executeQuery();
rs.next();
final InputStream is = rs.getBinaryStream(1);
final ByteArrayOutputStream os = new ByteArrayOutputStream();
final byte[] buffer = new byte[1024];
int count;
while ((count = is.read(buffer)) > 0) {
os.write(buffer, 0, count);
}
is.close();
os.close();
rs.close();
ps.close();
c.close();
return os.toByteArray();
} catch (final Exception e) {
throw new EJBException(e);
}
}
/**
* Test that the client throws an exception when an exception is thrown on
* the server side when streaming from the database.
*/
public void testInterruptedReadOfLob()
throws IOException, SQLException {
PreparedStatement fetchLobSt = prepareStatement(
"select TEST_COL from TEST_TABLE");
ResultSet rs = fetchLobSt.executeQuery();
try {
rs.next();
InputStream is = rs.getBinaryStream(1);
// Read the stream.
int c;
while ( (c = is.read() ) > -1) {}
fail("Reading stream should have raised exception.");
} catch (SQLException sqle) {
assertSQLState("58009", sqle);
}
rs.close();
fetchLobSt.close();
}
/**
* <p>
* This method should be overridden by any delegate subclasses that need
* special handling for BLOBs. The default implementation uses standard
* JDBC <code>java.sql.Blob</code> operations.
* </p>
*
* @param rs
* the result set, already queued to the correct row
* @param colName
* the column name for the BLOB
* @return the deserialized Object from the ResultSet BLOB
* @throws ClassNotFoundException
* if a class found during deserialization cannot be found
* @throws IOException
* if deserialization causes an error
*/
@Override
protected Object getObjectFromBlob(ResultSet rs, String colName)
throws ClassNotFoundException, IOException, SQLException {
InputStream binaryInput = rs.getBinaryStream(colName);
if(binaryInput == null || binaryInput.available() == 0) {
return null;
}
Object obj = null;
ObjectInputStream in = new ObjectInputStream(binaryInput);
try {
obj = in.readObject();
} finally {
in.close();
}
return obj;
}
private static void checkBlob(ResultSet rs, int index, byte[] expected, int key) {
try {
byte[] actual = rs.getBytes(index);
Assert.assertArrayEquals(expected, actual);
if (expected != null) {
DataInputStream dataInputStream = new DataInputStream(rs.getBinaryStream(index));
byte[] actualFromStream = new byte[actual.length];
dataInputStream.readFully(actualFromStream);
Assert.assertArrayEquals("error at key " + key, expected, actualFromStream);
Blob blob = rs.getBlob(index);
assertEquals("error at key " + key, blob.length(), actual.length);
DataInputStream dataInputStream2 = new DataInputStream(blob.getBinaryStream());
byte[] actualFromStream2 = new byte[actual.length];
dataInputStream2.readFully(actualFromStream2);
Assert.assertArrayEquals("error at key " + key, expected, actualFromStream2);
}
byte[] object = (byte[]) rs.getObject(index);
Assert.assertArrayEquals((byte[]) expected, object);
} catch (SQLException | IOException e) {
throw new RuntimeException(e);
}
}
/**
* <p>
* This method should be overridden by any delegate subclasses that need
* special handling for BLOBs. The default implementation uses standard
* JDBC <code>java.sql.Blob</code> operations.
* </p>
*
* @param rs
* the result set, already queued to the correct row
* @param colName
* the column name for the BLOB
* @return the deserialized Object from the ResultSet BLOB
* @throws ClassNotFoundException
* if a class found during deserialization cannot be found
* @throws IOException
* if deserialization causes an error
*/
protected Object getObjectFromBlob(ResultSet rs, String colName)
throws ClassNotFoundException, IOException, SQLException {
InputStream binaryInput = rs.getBinaryStream(colName);
if(binaryInput == null || binaryInput.available() == 0) {
return null;
}
Object obj = null;
ObjectInputStream in = new ObjectInputStream(binaryInput);
try {
obj = in.readObject();
} finally {
in.close();
}
return obj;
}
@Override
@Nullable
public InputStream getBlobAsBinaryStream(ResultSet rs, int columnIndex) throws SQLException {
logger.debug("Returning BLOB as binary stream");
if (this.wrapAsLob) {
Blob blob = rs.getBlob(columnIndex);
return blob.getBinaryStream();
}
else {
return rs.getBinaryStream(columnIndex);
}
}
public Collection<DestinationSequence> getDestinationSequences(String endpointIdentifier) {
if (LOG.isLoggable(Level.FINE)) {
LOG.info("Getting destination sequences for endpoint: " + endpointIdentifier);
}
Connection con = verifyConnection();
PreparedStatement stmt = null;
SQLException conex = null;
Collection<DestinationSequence> seqs = new ArrayList<>();
ResultSet res = null;
try {
stmt = getStatement(con, SELECT_DEST_SEQUENCES_STMT_STR);
stmt.setString(1, endpointIdentifier);
res = stmt.executeQuery();
while (res.next()) {
Identifier sid = new Identifier();
sid.setValue(res.getString(1));
EndpointReferenceType acksTo = RMUtils.createReference(res.getString(2));
long lm = res.getLong(3);
ProtocolVariation pv = decodeProtocolVersion(res.getString(4));
boolean t = res.getBoolean(5);
InputStream is = res.getBinaryStream(6);
SequenceAcknowledgement ack = null;
if (null != is) {
ack = PersistenceUtils.getInstance()
.deserialiseAcknowledgment(is);
}
DestinationSequence seq = new DestinationSequence(sid, acksTo, lm, t, ack, pv);
seqs.add(seq);
}
} catch (SQLException ex) {
conex = ex;
LOG.log(Level.WARNING, new Message("SELECT_DEST_SEQ_FAILED_MSG", LOG).toString(), ex);
} finally {
releaseResources(stmt, res);
updateConnectionState(con, conex);
}
return seqs;
}
@Override
protected Object getJobDataFromBlob(ResultSet rs, String colName)
throws ClassNotFoundException, IOException, SQLException {
if (canUseProperties()) {
InputStream binaryInput = rs.getBinaryStream(colName);
return binaryInput;
}
return getObjectFromBlob(rs, colName);
}
static void get_using_binary_stream(ResultSet rs, int col_no) throws Exception{
System.out.println("getBinaryStream(" + col_no + ")");
int no_bytes_read = 0;
InputStream rsbin = rs.getBinaryStream(col_no);
byte [] bytearray = new byte[200];
int count = 0;
while((no_bytes_read=rsbin.read(bytearray)) != -1)
{
count = printbytearray(bytearray, no_bytes_read, count);
}
System.out.println("");
}
/**
* Delegates to {@link ResultSet#getObject(int, Class)} without throwing a {@link AbstractMethodError}.
* <p>
* If the JDBC driver does not implement {@link ResultSet#getObject(int, Class)}, then return 0.
* </p>
*
* @param <T>
* See {@link ResultSet#getObject(int, Class)}
* @param resultSet
* See {@link ResultSet#getObject(int, Class)}
* @param columnIndex
* See {@link ResultSet#getObject(int, Class)}
* @param type
* See {@link ResultSet#getObject(int, Class)}
* @return See {@link ResultSet#getObject(int, Class)}
* @throws SQLException
* See {@link ResultSet#getObject(int, Class)}
* @see ResultSet#getObject(int, Class)
*/
@SuppressWarnings("unchecked")
public static <T> T getObject(final ResultSet resultSet, final int columnIndex, final Class<T> type)
throws SQLException {
try {
return resultSet.getObject(columnIndex, type);
} catch (final AbstractMethodError e) {
if (type == String.class) {
return (T) resultSet.getString(columnIndex);
}
// Numbers
if (type == Integer.class) {
return (T) Integer.valueOf(resultSet.getInt(columnIndex));
}
if (type == Long.class) {
return (T) Long.valueOf(resultSet.getLong(columnIndex));
}
if (type == Double.class) {
return (T) Double.valueOf(resultSet.getDouble(columnIndex));
}
if (type == Float.class) {
return (T) Float.valueOf(resultSet.getFloat(columnIndex));
}
if (type == Short.class) {
return (T) Short.valueOf(resultSet.getShort(columnIndex));
}
if (type == BigDecimal.class) {
return (T) resultSet.getBigDecimal(columnIndex);
}
if (type == Byte.class) {
return (T) Byte.valueOf(resultSet.getByte(columnIndex));
}
// Dates
if (type == Date.class) {
return (T) resultSet.getDate(columnIndex);
}
if (type == Time.class) {
return (T) resultSet.getTime(columnIndex);
}
if (type == Timestamp.class) {
return (T) resultSet.getTimestamp(columnIndex);
}
// Streams
if (type == InputStream.class) {
return (T) resultSet.getBinaryStream(columnIndex);
}
if (type == Reader.class) {
return (T) resultSet.getCharacterStream(columnIndex);
}
// Other
if (type == Object.class) {
return (T) resultSet.getObject(columnIndex);
}
if (type == Boolean.class) {
return (T) Boolean.valueOf(resultSet.getBoolean(columnIndex));
}
if (type == Array.class) {
return (T) resultSet.getArray(columnIndex);
}
if (type == Blob.class) {
return (T) resultSet.getBlob(columnIndex);
}
if (type == Clob.class) {
return (T) resultSet.getClob(columnIndex);
}
if (type == Ref.class) {
return (T) resultSet.getRef(columnIndex);
}
if (type == RowId.class) {
return (T) resultSet.getRowId(columnIndex);
}
if (type == SQLXML.class) {
return (T) resultSet.getSQLXML(columnIndex);
}
if (type == URL.class) {
return (T) resultSet.getURL(columnIndex);
}
throw new SQLFeatureNotSupportedException(
String.format("resultSet=%s, columnIndex=%,d, type=%s", resultSet, Integer.valueOf(columnIndex), type));
}
}
/**
* Delegates to {@link ResultSet#getObject(int, Class)} without throwing an {@link AbstractMethodError}.
* <p>
* If the JDBC driver does not implement {@link ResultSet#getObject(int, Class)}, then return 0.
* </p>
*
* @param <T>
* See {@link ResultSet#getObject(int, Class)}
* @param resultSet
* See {@link ResultSet#getObject(int, Class)}
* @param columnIndex
* See {@link ResultSet#getObject(int, Class)}
* @param type
* See {@link ResultSet#getObject(int, Class)}
* @return See {@link ResultSet#getObject(int, Class)}
* @throws SQLException
* See {@link ResultSet#getObject(int, Class)}
* @see ResultSet#getObject(int, Class)
*/
@SuppressWarnings("unchecked")
public static <T> T getObject(final ResultSet resultSet, final int columnIndex, final Class<T> type)
throws SQLException {
try {
return resultSet.getObject(columnIndex, type);
} catch (final AbstractMethodError e) {
if (type == String.class) {
return (T) resultSet.getString(columnIndex);
}
// Numbers
if (type == Integer.class) {
return (T) Integer.valueOf(resultSet.getInt(columnIndex));
}
if (type == Long.class) {
return (T) Long.valueOf(resultSet.getLong(columnIndex));
}
if (type == Double.class) {
return (T) Double.valueOf(resultSet.getDouble(columnIndex));
}
if (type == Float.class) {
return (T) Float.valueOf(resultSet.getFloat(columnIndex));
}
if (type == Short.class) {
return (T) Short.valueOf(resultSet.getShort(columnIndex));
}
if (type == BigDecimal.class) {
return (T) resultSet.getBigDecimal(columnIndex);
}
if (type == Byte.class) {
return (T) Byte.valueOf(resultSet.getByte(columnIndex));
}
// Dates
if (type == Date.class) {
return (T) resultSet.getDate(columnIndex);
}
if (type == Time.class) {
return (T) resultSet.getTime(columnIndex);
}
if (type == Timestamp.class) {
return (T) resultSet.getTimestamp(columnIndex);
}
// Streams
if (type == InputStream.class) {
return (T) resultSet.getBinaryStream(columnIndex);
}
if (type == Reader.class) {
return (T) resultSet.getCharacterStream(columnIndex);
}
// Other
if (type == Object.class) {
return (T) resultSet.getObject(columnIndex);
}
if (type == Boolean.class) {
return (T) Boolean.valueOf(resultSet.getBoolean(columnIndex));
}
if (type == Array.class) {
return (T) resultSet.getArray(columnIndex);
}
if (type == Blob.class) {
return (T) resultSet.getBlob(columnIndex);
}
if (type == Clob.class) {
return (T) resultSet.getClob(columnIndex);
}
if (type == Ref.class) {
return (T) resultSet.getRef(columnIndex);
}
if (type == RowId.class) {
return (T) resultSet.getRowId(columnIndex);
}
if (type == SQLXML.class) {
return (T) resultSet.getSQLXML(columnIndex);
}
if (type == URL.class) {
return (T) resultSet.getURL(columnIndex);
}
throw new SQLFeatureNotSupportedException(
String.format("resultSet=%s, columnIndex=%,d, type=%s", resultSet, columnIndex, type));
}
}
private static String getValues(final ResultSet rs, final String columnName, final Integer columnType)
throws SQLException {
String res = null;
try {
switch (columnType) {
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
final InputStream is = rs.getBinaryStream(columnName);
if (is != null) {
res = DatatypeConverter.printHexBinary(IOUtils.toByteArray(is));
}
break;
case Types.BLOB:
final Blob blob = rs.getBlob(columnName);
if (blob != null) {
res = DatatypeConverter.printHexBinary(IOUtils.toByteArray(blob.getBinaryStream()));
}
break;
case Types.BIT:
case Types.BOOLEAN:
if (rs.getBoolean(columnName)) {
res = "1";
} else {
res = "0";
}
break;
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
final Timestamp timestamp = rs.getTimestamp(columnName);
if (timestamp != null) {
res = FormatUtils.format(new Date(timestamp.getTime()));
}
break;
default:
res = rs.getString(columnName);
}
} catch (IOException e) {
LOG.error("Error retrieving hexadecimal string", e);
}
return res;
}
@Override
public InputStream getBinaryStreamFromByteArray(ResultSet rs, String columnName) throws SQLException {
return rs.getBinaryStream(columnName);
}
private static void testReadOfLob()
throws SQLException,
IOException,
IllegalAccessException,
ClassNotFoundException,
InstantiationException
{
Connection conn =
getConnection();
conn.setAutoCommit(false);
PreparedStatement insertLobSt =
conn.prepareStatement("insert into TEST_TABLE( TEST_COL ) values(?)");
insertLobSt.setBinaryStream(1,
createOriginalDataInputStream( 65536 ),
65536 );
insertLobSt.executeUpdate();
insertLobSt.close();
conn.commit();
PreparedStatement st = conn.prepareStatement("select TEST_COL from TEST_TABLE");
ResultSet rs = st.executeQuery();
rs.next();
InputStream is = rs.getBinaryStream(1);
int c;
while( ( c = is.read() ) > -1 ){
System.out.print(c);
System.out.print(",");
if( ( (c + 1) % 256 ) == 0 )
System.out.println();
}
is.close();
rs.close();
st.close();
conn.commit();
conn.close();
System.out.println();
}
/**
* This methods tests the ResultSet interface method
* updateBinaryStream
*
* @throws SQLException if some error occurs while calling the method
*/
public void testUpdateBinaryStreamStringParameterName()
throws Exception {
//Byte array in which the returned bytes from
//the Database after the update are stored. This
//array is then checked to determine if it
//has the same elements of the Byte array used for
//the update operation
byte[] bytes_ret = new byte[10];
//Input Stream inserted initially
InputStream is = new java.io.ByteArrayInputStream(BYTES1);
//InputStream that is used for update
InputStream is_for_update = new
java.io.ByteArrayInputStream(BYTES2);
//Prepared Statement used to insert the data
PreparedStatement ps_sb = prep("dLongBit");
ps_sb.setInt(1, key);
ps_sb.setBinaryStream(2,is,BYTES1.length);
ps_sb.executeUpdate();
ps_sb.close();
//Update operation
//Update operation
//use a different ResultSet variable so that the
//other tests can go on unimpacted
ResultSet rs1 = fetchUpd("dLongBit", key);
rs1.next();
rs1.updateBinaryStream("dLongBit",is_for_update,(int)BYTES2.length);
rs1.updateRow();
rs1.close();
//Query to see whether the data that has been updated
//using the updateBinaryStream method is the same
//data that we expected
rs1 = fetch("dLongBit", key);
rs1.next();
InputStream is_ret = rs1.getBinaryStream(1);
is_ret.read(bytes_ret);
is_ret.close();
for(int i=0;i<BYTES2.length;i++) {
assertEquals("Error in updateBinaryStream",BYTES2[i],bytes_ret[i]);
}
rs1.close();
}
private static void testReadOfLob()
throws SQLException,
IOException,
IllegalAccessException,
ClassNotFoundException,
InstantiationException
{
Connection conn =
getConnection();
conn.setAutoCommit(false);
PreparedStatement insertLobSt =
conn.prepareStatement("insert into TEST_TABLE( TEST_COL ) values(?)");
insertLobSt.setBinaryStream(1,
createOriginalDataInputStream( 65536 ),
65536 );
insertLobSt.executeUpdate();
insertLobSt.close();
conn.commit();
PreparedStatement st = conn.prepareStatement("select TEST_COL from TEST_TABLE");
ResultSet rs = st.executeQuery();
rs.next();
InputStream is = rs.getBinaryStream(1);
int c;
while( ( c = is.read() ) > -1 ){
System.out.print(c);
System.out.print(",");
if( ( (c + 1) % 256 ) == 0 )
System.out.println();
}
is.close();
rs.close();
st.close();
conn.commit();
conn.close();
System.out.println();
}
/** convert resultset data for the current row to string array.
* If large objects are being exported to an external file,
* then write the lob data into the external file and store
* the lob data location in the string array for that column.
* @param rs resultset that contains the data to export.
* @param isLargeBinary boolean array, whose elements will
* be true, if the column type is blob/or
* other large binary type, otherwise false.
* @param isLargeChar boolean array, whose elements will
* be true, if the column type is clob/
* other large char type, otherwise false.
* @return A string array of the row data to write to export file.
* @exception Exception if any errors during conversion.
*/
private String[] getOneRowAtATime(ResultSet rs,
boolean[] isLargeBinary,
boolean[] isLargeChar)
throws Exception
{
int columnCount = exportResultSetForObject.getColumnCount();
ResultSetMetaData rsm=rs.getMetaData();
if (rs.next()){
String[] rowObjects = new String[columnCount];
for (int colNum = 0; colNum < columnCount; colNum++) {
if (lobsInExtFile &&
(isLargeChar[colNum] || isLargeBinary[colNum]))
{
String LobExtLocation;
if (isLargeBinary[colNum]) {
// get input stream that has the column value as a
// stream of uninterpreted bytes; if the value is SQL NULL,
// the return value is null
InputStream is = rs.getBinaryStream(colNum + 1);
LobExtLocation =
exportWriteData.writeBinaryColumnToExternalFile(is);
} else {
// It is clob data, get character stream that has
// the column value. if the value is SQL NULL, the
// return value is null
Reader ir = rs.getCharacterStream(colNum + 1);
LobExtLocation =
exportWriteData.writeCharColumnToExternalFile(ir);
}
rowObjects[colNum]= LobExtLocation;
// when lob data is written to the main export file, binary
// data is written in hex format. getString() call on binary
// columns returns the data in hex format, no special handling
// required. In case of large char tpe like Clob, data
// is written to main export file similar to other char types.
// TODO : handling of Nulls.
}
else {
String columnValue;
int jdbcColumnNumber = colNum + 1;
if ( rsm.getColumnType( jdbcColumnNumber ) == java.sql.Types.JAVA_OBJECT )
{ columnValue = stringifyObject( rs.getObject( jdbcColumnNumber ) ); }
else { columnValue = rs.getString( jdbcColumnNumber ); }
rowObjects[colNum] = columnValue;
}
}
return rowObjects;
}
rs.close();
exportResultSetForObject.close();
return null;
}
@Override
public InputStream getStream( String request ) throws Exception
{
Connection conn = connection;
// If no given connection, create one from the DataSource.
if (connection == null)
{
conn = dataSource.getConnection();
}
InputStream input = null;
try
{
// Prepares the query for execution.
PreparedStatement statement = conn.prepareStatement( query );
try
{
// Places the request string in the query.
statement.setString( 1, request );
// Executes the query.
ResultSet results = statement.executeQuery();
try
{
// If results were returned, read them in as a binary stream.
if (results.next())
{
input = results.getBinaryStream( 1 );
}
}
finally
{
results.close();
}
}
finally
{
statement.close();
}
}
finally
{
// If a connection was created from the DataSource make sure to
// close it.
if (connection == null)
{
conn.close();
}
}
return input;
}
/**
* This methods tests the ResultSet interface method
* updateBinaryStream
*
* @throws SQLException if some error occurs while calling the method
*/
public void testUpdateBinaryStream()
throws Exception {
//Byte array in which the returned bytes from
//the Database after the update are stored. This
//array is then checked to determine if it
//has the same elements of the Byte array used for
//the update operation
byte[] bytes_ret = new byte[10];
//Input Stream inserted initially
InputStream is = new java.io.ByteArrayInputStream(BYTES1);
//InputStream that is used for update
InputStream is_for_update = new
java.io.ByteArrayInputStream(BYTES2);
//Prepared Statement used to insert the data
PreparedStatement ps_sb = prep("dLongBit");
ps_sb.setInt(1,key);
ps_sb.setBinaryStream(2,is,BYTES1.length);
ps_sb.executeUpdate();
ps_sb.close();
//Update operation
//use a different ResultSet variable so that the
//other tests can go on unimpacted
ResultSet rs1 = fetchUpd("dLongBit", key);
rs1.next();
rs1.updateBinaryStream(1,is_for_update,(int)BYTES2.length);
rs1.updateRow();
rs1.close();
//Query to see whether the data that has been updated
//using the updateBinaryStream method is the same
//data that we expected
rs1 = fetch("dLongBit", key);
rs1.next();
InputStream is_ret = rs1.getBinaryStream(1);
is_ret.read(bytes_ret);
is_ret.close();
for(int i=0;i<BYTES2.length;i++) {
assertEquals("Error in updateBinaryStream",BYTES2[i],bytes_ret[i]);
}
rs1.close();
}