java.sql.ResultSet#getBlob ( )源码实例Demo

下面列出了java.sql.ResultSet#getBlob ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: AsuraFramework   文件: WebLogicDelegate.java
/**
 * <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 {
    
    Object obj = null;

    Blob blobLocator = rs.getBlob(colName);
    InputStream binaryInput = null;
    try {
        if (null != blobLocator && blobLocator.length() > 0) {
            binaryInput = blobLocator.getBinaryStream();
        }
    } catch (Exception ignore) {
    }

    if (null != binaryInput) {
        ObjectInputStream in = new ObjectInputStream(binaryInput);
        try {
            obj = in.readObject();
        } finally {
            in.close();
        }
    }

    return obj;
}
 
源代码2 项目: gemfirexd-oss   文件: EXTDTAInputStream.java
/**
	 * Create a new EXTDTAInputStream.  Before read the stream must be 
     * initialized by the user with {@link #initInputStream()} 
	 * 
	 * @see DDMWriter#writeScalarStream
     * @see #initInputStream()
	 * 
	 * @param rs
	 *            result set from which to retrieve the lob
	 * @param column
	 *            column number
	 * @param drdaType
	 *            FD:OCA type of object one of
	 * 			   DRDAConstants.DRDA_TYPE_NLOBBYTES
	 * 			   DRDAConstants.DRDA_TYPE_LOBBYTES
	 * 			   DRDAConstants.DRDA_TYPE_NLOBCMIXED
	 *  		   DRDAConstants.DRDA_TYPE_LOBCMIXED
	 * 
	 * @return null if the value is null or a new EXTDTAInputStream corresponding to 
	 *  		rs.getBinaryStream(column) value and associated length
	 * 
	 * @throws SQLException
	 */
	public static EXTDTAInputStream getEXTDTAStream(ResultSet rs, int column, int drdaType)
// GemStone changes BEGIN
	throws SQLException
// GemStone changes END
		{
 	    
		int ndrdaType = drdaType | 1; //nullable drdaType
			
// GemStone changes BEGIN
		if (!(rs instanceof EngineResultSet)) {
		  switch (ndrdaType) {
		    case DRDAConstants.DRDA_TYPE_NLOBBYTES:
		      Blob blob = rs.getBlob(column);
		      return blob != null
		          ? new EXTDTAInputStream(blob,ndrdaType) : null;
		    case DRDAConstants.DRDA_TYPE_NLOBCMIXED:
		      Clob clob = rs.getClob(column);
		      return clob != null
		          ? new EXTDTAInputStream(clob, ndrdaType) : null;
		    default:
		      badDRDAType(ndrdaType);
		      return null;
		  }
	        }
// GemStone changes END
		return new EXTDTAInputStream(rs,
					     column,
					     ndrdaType);
		
	}
 
源代码3 项目: tangyuan2   文件: BlobTypeHandler.java
@Override
public byte[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
	Blob blob = rs.getBlob(columnName);
	byte[] returnValue = null;
	if (null != blob) {
		returnValue = blob.getBytes(1, (int) blob.length());
	}
	return returnValue;
}
 
public Object getSource(String id, ResultSet rs) throws SQLException
{
	ResultSetMetaData metadata = rs.getMetaData();
	String rv = null;
	switch(metadata.getColumnType(1))
	{
	case Types.BLOB:
		Blob blob = rs.getBlob(1);
		if(blob != null)
		{
			rv = new String(blob.getBytes(1L, (int) blob.length()));
		}
		break;
	case Types.CLOB:
		Clob clob = rs.getClob(1);
		if(clob != null)
		{
			rv = clob.getSubString(1L, (int) clob.length());
		}
		break;
	case Types.CHAR:
	case Types.LONGVARCHAR:
	case Types.VARCHAR:
	case Types.BINARY:
	case Types.VARBINARY:
	case Types.LONGVARBINARY:
		byte[] bytes = rs.getBytes(1);
		if(bytes != null)
		{
			rv = new String(bytes);
		}
		break;
	}
	return rv;
}
 
源代码5 项目: mybaties   文件: BlobTypeHandler.java
@Override
public byte[] getNullableResult(ResultSet rs, String columnName)
    throws SQLException {
  Blob blob = rs.getBlob(columnName);
  byte[] returnValue = null;
  if (null != blob) {
    returnValue = blob.getBytes(1, (int) blob.length());
  }
  return returnValue;
}
 
源代码6 项目: kylin-on-parquet-v2   文件: JDBCResourceStore.java
private InputStream getInputStream(String resPath, ResultSet rs) throws SQLException, IOException {
    if (rs == null) {
        return null;
    }

    Blob blob = rs.getBlob(META_TABLE_CONTENT);

    if (blob == null || blob.length() == 0) {
        return openPushdown(resPath); // empty bytes is pushdown indicator
    } else {
        return blob.getBinaryStream();
    }
}
 
源代码7 项目: spliceengine   文件: LobLimitsTest.java
/**
 * select from blob table (BLOBTBL2)
 * 
 * @param bloblen select expects to retrieve a blob of this length
 * @param id id of the row to retrieve
 * @param expectedRows number of rows expected to match id
 * @param file name of the file,against which the retrieved data is compared
 */
private void selectBlob2(String testId,
        PreparedStatement ps, int bloblen, int id, int expectedRows,
        String file) throws Exception {
    println("========================================");
    println("START " + testId + " - SELECT BLOB of size = "
            + bloblen);

    long ST = System.currentTimeMillis();

    int count = 0;
    ps.setInt(1, id);
    ResultSet rs = ps.executeQuery();

    while (rs.next()) {
        count++;
        Blob value = rs.getBlob(1);
        long l = value.length();
        long dlen = rs.getLong(2);
        assertEquals("FAIL - MISMATCH LENGTHS GOT " + l
                   + " expected " + dlen + " for row in BLOBTBL with ID="
                   + id, dlen, l);

        compareBlobToFile(value.getBinaryStream(), file);
    }

    rs.close();
    commit();

    verifyTest(count, expectedRows,
            "Matched rows selected with blob of size(" + bloblen + ") =");

    println("Select Blob (" + bloblen + ")" + " rows= "
               + expectedRows + " = "
               + (long) (System.currentTimeMillis() - ST));
    println("========================================");
}
 
protected InputStream getBlobAsInputStream(ResultSet rs, int col) throws SQLException
{
    if(_useBytesMethodsForBlob)
    {
        return new ByteArrayInputStream(rs.getBytes(col));
    }
    else
    {
        Blob dataAsBlob = rs.getBlob(col);
        return dataAsBlob.getBinaryStream();
    }
}
 
源代码9 项目: qpid-broker-j   文件: DerbyUtils.java
public static String getBlobAsString(ResultSet rs, int col) throws SQLException
{
    Blob blob = rs.getBlob(col);
    if(blob == null)
    {
        return null;
    }
    byte[] bytes = blob.getBytes(1, (int) blob.length());
    return new String(bytes, StandardCharsets.UTF_8);
}
 
源代码10 项目: gemfirexd-oss   文件: LOBLocatorReleaseTest.java
/**
 * Tests that the LOB objects are not closed when closing the result set.
 *
 * @throws SQLException if something causes the test to fail
 */
public void testBlobClobStateForwardOnlyWithNoNulls()
        throws SQLException {
    getConnection().setAutoCommit(false);
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery(
            "select dBlob, dClob from LOBLOC_NO_NULLS");
    rs.next();
    Blob b = rs.getBlob(1);
    final long blobLength = b.length();
    rs.next();
    Clob c = rs.getClob(2);
    final long clobLength = c.length();
    rs.next();
    rs.close();
    // The LOB objects should still be usable.
    assertEquals(blobLength, b.length());
    assertEquals(clobLength, c.length());
    commit();
    try {
        // This should fail because the locator has been released.
        c.getSubString(1, 9);
        fail("Locator should have been released, causing the call to fail");
    } catch (SQLException sqle) {
        assertSQLState("XJ215", sqle);
    }
}
 
public Object getSource(String id, ResultSet rs) throws SQLException
{
	ResultSetMetaData metadata = rs.getMetaData();
	String rv = null;
	switch(metadata.getColumnType(1))
	{
	case Types.BLOB:
		Blob blob = rs.getBlob(1);
		if(blob != null)
		{
			rv = new String(blob.getBytes(1L, (int) blob.length()));
		}
		break;
	case Types.CLOB:
		Clob clob = rs.getClob(1);
		if(clob != null)
		{
			rv = clob.getSubString(1L, (int) clob.length());
		}
		break;
	case Types.CHAR:
	case Types.LONGVARCHAR:
	case Types.VARCHAR:
	case Types.BINARY:
	case Types.VARBINARY:
	case Types.LONGVARBINARY:
		byte[] bytes = rs.getBytes(1);
		if(bytes != null)
		{
			rv = new String(bytes);
		}
		break;
	}
	return rv;
}
 
源代码12 项目: Tomcat8-Source-Read   文件: Jdbc41Bridge.java
/**
 * Delegates to {@link ResultSet#getObject(String, Class)} without throwing a {@link AbstractMethodError}.
 *
 * @param <T>
 *            See {@link ResultSet#getObject(String, Class)}
 * @param resultSet
 *            See {@link ResultSet#getObject(String, Class)}
 * @param columnLabel
 *            See {@link ResultSet#getObject(String, Class)}
 * @param type
 *            See {@link ResultSet#getObject(String, Class)}
 * @return See {@link ResultSet#getObject(String, Class)}
 * @throws SQLException
 *             See {@link ResultSet#getObject(String, Class)}
 * @see ResultSet#getObject(int, Class)
 */
@SuppressWarnings("unchecked")
public static <T> T getObject(final ResultSet resultSet, final String columnLabel, final Class<T> type)
        throws SQLException {
    try {
        return resultSet.getObject(columnLabel, type);
    } catch (final AbstractMethodError e) {
        // Numbers
        if (type == Integer.class) {
            return (T) Integer.valueOf(resultSet.getInt(columnLabel));
        }
        if (type == Long.class) {
            return (T) Long.valueOf(resultSet.getLong(columnLabel));
        }
        if (type == Double.class) {
            return (T) Double.valueOf(resultSet.getDouble(columnLabel));
        }
        if (type == Float.class) {
            return (T) Float.valueOf(resultSet.getFloat(columnLabel));
        }
        if (type == Short.class) {
            return (T) Short.valueOf(resultSet.getShort(columnLabel));
        }
        if (type == BigDecimal.class) {
            return (T) resultSet.getBigDecimal(columnLabel);
        }
        if (type == Byte.class) {
            return (T) Byte.valueOf(resultSet.getByte(columnLabel));
        }
        // Dates
        if (type == Date.class) {
            return (T) resultSet.getDate(columnLabel);
        }
        if (type == Time.class) {
            return (T) resultSet.getTime(columnLabel);
        }
        if (type == Timestamp.class) {
            return (T) resultSet.getTimestamp(columnLabel);
        }
        // Streams
        if (type == InputStream.class) {
            return (T) resultSet.getBinaryStream(columnLabel);
        }
        if (type == Reader.class) {
            return (T) resultSet.getCharacterStream(columnLabel);
        }
        // Other
        if (type == Object.class) {
            return (T) resultSet.getObject(columnLabel);
        }
        if (type == Boolean.class) {
            return (T) Boolean.valueOf(resultSet.getBoolean(columnLabel));
        }
        if (type == Array.class) {
            return (T) resultSet.getArray(columnLabel);
        }
        if (type == Blob.class) {
            return (T) resultSet.getBlob(columnLabel);
        }
        if (type == Clob.class) {
            return (T) resultSet.getClob(columnLabel);
        }
        if (type == Ref.class) {
            return (T) resultSet.getRef(columnLabel);
        }
        if (type == RowId.class) {
            return (T) resultSet.getRowId(columnLabel);
        }
        if (type == SQLXML.class) {
            return (T) resultSet.getSQLXML(columnLabel);
        }
        if (type == URL.class) {
            return (T) resultSet.getURL(columnLabel);
        }
        throw new SQLFeatureNotSupportedException(
                String.format("resultSet=%s, columnLabel=%s, type=%s", resultSet, columnLabel, type));
    }
}
 
源代码13 项目: spliceengine   文件: LobStreamsTest.java
/**
 * Tests the BlobOutputStream.write(int b) method
 **/
public void testBlobWrite1Param() throws Exception {
    InputStream streamIn = new LoopingAlphabetStream(streamSize[1]);

    PreparedStatement stmt3 = prepareStatement(
        "SELECT b FROM testBlobX1 WHERE a = 1");
    ResultSet rs3 = stmt3.executeQuery();
    rs3.next();
    Blob blob = rs3.getBlob(1);

    assertTrue("FAIL -- blob is NULL", blob != null);

    int buffer;
    OutputStream outstream = blob.setBinaryStream(1L);
    while ((buffer = streamIn.read()) != -1) {
        outstream.write(buffer);
    }
    outstream.close();
    streamIn.close();

    PreparedStatement stmt4 = prepareStatement(
        "UPDATE testBlobX1 SET b = ? WHERE a = 1");
    stmt4.setBlob(1,  blob);
    stmt4.executeUpdate();
    stmt4.close();

    rs3.close();
    rs3 = stmt3.executeQuery();

    assertTrue("FAIL -- blob not found", rs3.next());

    blob = rs3.getBlob(1);
    long new_length = blob.length();
    assertEquals("FAIL -- wrong blob length", streamSize[1], new_length);

    // Check contents ...
    InputStream fStream = new LoopingAlphabetStream(streamSize[1]);
    InputStream lStream = blob.getBinaryStream();
    assertTrue("FAIL - Blob and file contents do not match",
            compareLob2File(fStream, lStream));

    fStream.close();
    lStream.close();
    rs3.close();
    stmt3.close();
}
 
源代码14 项目: spliceengine   文件: LOBLocatorReleaseTest.java
private void forwardOnlyTest(String table)
        throws SQLException {
    final String sql = "select dBlob, dClob from " + table;
    getConnection().setAutoCommit(false);
    // Just loop through.
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery(sql);
    while (rs.next()) {
        // Just iterate through.
    }
    rs.close();

    // Loop through and get references to some of the LOBs.
    // When you get a LOB reference, the locator shuold only be freed on
    // explicit calls to free (requires Java SE 6) or commit/rollback.
    rs = stmt.executeQuery(sql);
    int index = 0;
    while (rs.next()) {
        if (index % 2 == 0) {
            Blob b = rs.getBlob(1);
            if (!rs.wasNull()) {
                b.length();
            }
        }
        if (index % 3 == 0) {
            Clob c = rs.getClob(2);
            if (!rs.wasNull()) {
                c.length();
            }
        }
        // Clear all LOB mappings after 10 rows.
        if (index == 9) {
            commit();
        }
        index++;
    }
    rs.close();
    stmt.close();

    // Close the statement after a few rows.
    stmt = createStatement();
    rs = stmt.executeQuery(sql);
    rs.next();
    rs.next();
    stmt.close();
    // The LOB mapping is cleared on a commit.
    commit();

    // Close the result set after a few rows and a rollback.
    stmt = createStatement();
    rs = stmt.executeQuery(sql);
    rs.next();
    rs.next();
    rollback();
    rs.close();
}
 
源代码15 项目: gemfirexd-oss   文件: ResultSetTest.java
/**
 * This methods tests the ResultSet interface method
 * updateBlob
 *
 * @throws SQLException if some error occurs while calling the method
 */
public void testUpdateBlobStringParameterName()
throws Exception {
    // Life span of Blob objects are limited by the transaction.  Need
    // autocommit off so Blob objects survive execution of next statement.
    getConnection().setAutoCommit(false);

    //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];

    //1 Input Stream for insertion
    InputStream is1 = new java.io.ByteArrayInputStream(BYTES1);

    //2 Input Stream for insertion
    InputStream is2 = new java.io.ByteArrayInputStream(BYTES2);

    //Prepared Statement used to insert the data
    PreparedStatement ps_sb = prep("dBlob");

    //first insert
    ps_sb.setInt(1, key);
    ps_sb.setBinaryStream(2,is1,BYTES1.length);
    ps_sb.executeUpdate();

    //second insert
    int key2 = requestKey();
    ps_sb.setInt(1, key2);
    ps_sb.setBinaryStream(2,is2,BYTES2.length);
    ps_sb.executeUpdate();

    ps_sb.close();

    //Update operation
    //use a different ResultSet variable so that the
    //other tests can go on unimpacted
    //we do not have set methods on Clob and Blob implemented
    //So query the first Clob from the database
    //update the second result set with this
    //Clob value

    ResultSet rs1 = fetch("dBlob", key);
    rs1.next();
    Blob blob = rs1.getBlob(1);
    rs1.close();

    rs1 = fetchUpd("dBlob", key2);
    rs1.next();
    rs1.updateBlob("dBlob",blob);
    rs1.updateRow();
    rs1.close();

    //Query to see whether the data that has been updated
    //using the updateBlob method is the same
    //data that we expected

    rs1 = fetch("dBlob", key2);
    rs1.next();
    assertEquals(blob, rs1.getBlob(1)); 
    rs1.close();
}
 
源代码16 项目: gemfirexd-oss   文件: BlobTestsDUnit.java
/**
 * tests set bytes method of blob in memory only mode (less than 4k)
 */
public void testSetBytesSmallBlob() throws Exception {
  startVMs(1, 4);

  Connection con = TestUtil.getConnection();
  Statement stmt = con.createStatement();
  stmt.execute("create table blobtest (id integer, data Blob)");
  stmt.close();

  con.setAutoCommit(false);
  PreparedStatement pstmt = con.prepareStatement("insert into "
      + "blobtest (id, data) values (?,?)");
  pstmt.setInt(1, 1);
  Blob blob = con.createBlob();
  // add 1024 bytes
  byte[] data = new byte[BUFFER_SIZE];
  for (int i = 0; i < BUFFER_SIZE; i++) {
    data[i] = (byte)(i % 255);
  }
  blob.setBytes(1, data);
  assertEquals(BUFFER_SIZE, blob.length());
  pstmt.setBlob(2, blob);
  pstmt.executeUpdate();

  stmt = con.createStatement();
  ResultSet rs = stmt.executeQuery("select data from blobtest where id = 1");
  assertEquals(true, rs.next());
  blob = rs.getBlob(1);
  assertEquals(BUFFER_SIZE, blob.length());
  // update blob in the middle
  byte[] data1 = new byte[UPDATE_SIZE];
  for (int i = 0; i < UPDATE_SIZE; i++)
    data1[i] = 120;// just any value
  blob.setBytes(UPDATE_SIZE, data1);
  byte[] data2 = blob.getBytes(100, UPDATE_SIZE);
  for (int i = 0; i < UPDATE_SIZE; i++)
    assertEquals(data1[i], data2[i]);
  // update it at the end
  blob.setBytes(BUFFER_SIZE + 1, data1);
  assertEquals(BUFFER_SIZE + UPDATE_SIZE, blob.length());
  data2 = blob.getBytes(BUFFER_SIZE + 1, UPDATE_SIZE);
  for (int i = 0; i < UPDATE_SIZE; i++)
    assertEquals(data1[i], data2[i]);
  // insert the blob and test again
  pstmt.setInt(1, 2);
  pstmt.setBlob(2, blob);
  pstmt.executeUpdate();
  rs = stmt.executeQuery("select data from blobtest where id = 2");
  assertEquals(true, rs.next());
  blob = rs.getBlob(1);
  assertEquals(BUFFER_SIZE + UPDATE_SIZE, blob.length());
  data2 = blob.getBytes(100, UPDATE_SIZE);
  for (int i = 0; i < UPDATE_SIZE; i++)
    assertEquals(data1[i], data2[i]);
  data2 = blob.getBytes(BUFFER_SIZE + 1, UPDATE_SIZE);
  for (int i = 0; i < UPDATE_SIZE; i++)
    assertEquals(data1[i], data2[i]);

  // test truncate on small size blob
  blob = con.createBlob();
  data = new byte[100];
  for (int i = 0; i < 100; i++) {
    data[i] = (byte)i;
  }
  blob.setBytes(1, data);
  assertEquals(blob.length(), 100);
  blob.truncate(50);
  assertEquals(blob.length(), 50);
  blob.setBytes(1, data);
  assertEquals("set failed", blob.length(), 100);
  blob.truncate(50);
  assertEquals("truncation failed", blob.length(), 50);
  rs.close();
  con.commit();
  stmt.close();
  pstmt.close();

  stmt = con.createStatement();
  stmt.execute("drop table blobtest");
  stmt.close();
}
 
源代码17 项目: mango   文件: BlobByteObjectArrayTypeHandler.java
@Override
public Byte[] getNullableResult(ResultSet rs, int columnIndex)
    throws SQLException {
  Blob blob = rs.getBlob(columnIndex);
  return getBytes(blob);
}
 
源代码18 项目: gemfirexd-oss   文件: ConnectionMethodsTest.java
/**
 * Test the createBlob method implementation in the Connection interface
 *
 * @exception  SQLException, FileNotFoundException, Exception if error occurs
 */
public void testCreateBlob() throws   SQLException,
        FileNotFoundException,
        IOException,
        Exception{

    Connection conn = getConnection();
    int b, c;
    Blob blob;

    Statement s = createStatement();
    PreparedStatement ps =
            prepareStatement("insert into blobtable2 (n, blobcol)" + " values(?,?)");
    ps.setInt(1,1000);
    blob = conn.createBlob();

    try {
        is = (FileInputStream) AccessController.doPrivileged(
                new PrivilegedExceptionAction() {
            public Object run() throws FileNotFoundException {
                return new FileInputStream("extin/short.txt");
            }
        });
    } catch (PrivilegedActionException e) {
        // e.getException() should be an instance of FileNotFoundException,
        // as only "checked" exceptions will be "wrapped" in a
        // PrivilegedActionException.
        throw (FileNotFoundException) e.getException();
    }

    OutputStream os = blob.setBinaryStream(1);
    ArrayList beforeUpdateList = new ArrayList();

    int actualLength = 0;
    c = is.read();
    while(c>0) {
        os.write(c);
        beforeUpdateList.add(c);
        c = is.read();
        actualLength ++;
    }
    ps.setBlob(2, blob);
    ps.executeUpdate();

    Statement stmt = createStatement();
    ResultSet rs =
            stmt.executeQuery("select blobcol from blobtable2 where n = 1000");
    assertTrue(rs.next());

    blob = rs.getBlob(1);
    assertEquals(beforeUpdateList.size(), blob.length());

    //Get the InputStream from this Blob.
    InputStream in = blob.getBinaryStream();
    ArrayList afterUpdateList = new ArrayList();

    b = in.read();

    while (b > -1) {
        afterUpdateList.add(b);
        b = in.read();
    }

    assertEquals(beforeUpdateList.size(), afterUpdateList.size());

    //Now check if the two InputStreams
    //match
    for (int i = 0; i < blob.length(); i++) {
        assertEquals(beforeUpdateList.get(i), afterUpdateList.get(i));
    }

    os.close();
    is.close();
}
 
源代码19 项目: gemfirexd-oss   文件: BlobSetMethodsTest.java
/**
 * Tests large blob (more than 4k) to ensure LOBStreamControl uses file.
 */
public void testSetBytesLargeBlob () throws SQLException {
    Connection con = getConnection();
    con.setAutoCommit (false);
    PreparedStatement pstmt = con.prepareStatement("insert into " +
            "blobtest (id, data) values (?,?)");
    Blob blob = con.createBlob();
    byte [] data = new byte [BUFFER_SIZE];
    for (int i = 0; i < BUFFER_SIZE; i++) {
        data [i] = (byte) (i % 255);
    }
 //now add more than 4k so file get in use
    for (int i = 0; i < 5; i++)
        blob.setBytes (i * BUFFER_SIZE + 1, data);
    assertEquals (BUFFER_SIZE * 5 , blob.length());
                //update blob in the middle
    byte [] data1 = new byte [UPDATE_SIZE];
    for (int i = 0; i < UPDATE_SIZE; i++)
        data1 [i] = 120;//just any value
    blob.setBytes (BUFFER_SIZE + 1, data1);
    blob.setBytes (BUFFER_SIZE * 5 + 1, data1);
    assertEquals (5 * BUFFER_SIZE + UPDATE_SIZE, blob.length());
    //insert it into table
    pstmt.setInt (1, 3);
    pstmt.setBlob (2, blob);
    pstmt.executeUpdate ();
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("select data from blobtest where " +
                            "id = 3");
    assertEquals(true, rs.next());
    blob = rs.getBlob (1);
    byte [] data2 = blob.getBytes (BUFFER_SIZE + 1, UPDATE_SIZE);
    assertEquals (5 * BUFFER_SIZE + UPDATE_SIZE, blob.length());
    for (int i = 0; i < UPDATE_SIZE; i++)
        assertEquals (data1 [i], data2 [i]);
    data2 = blob.getBytes (5 * BUFFER_SIZE + 1, UPDATE_SIZE);
    for (int i = 0; i < UPDATE_SIZE; i++)
        assertEquals (data1 [i], data2 [i]);
    //test truncate
    blob.truncate (BUFFER_SIZE);
    assertEquals ("truncate failed", BUFFER_SIZE, blob.length());
    rs.close();
    con.commit();
    stmt.close();
    pstmt.close();
}
 
源代码20 项目: lams   文件: StdJDBCDelegate.java
/**
 * <p>
 * This method should be overridden by any delegate subclasses that need
 * special handling for BLOBs for job details. 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 getJobDataFromBlob(ResultSet rs, String colName)
    throws ClassNotFoundException, IOException, SQLException {
    if (canUseProperties()) {
        Blob blobLocator = rs.getBlob(colName);
        if (blobLocator != null) {
            InputStream binaryInput = blobLocator.getBinaryStream();
            return binaryInput;
        } else {
            return null;
        }
    }

    return getObjectFromBlob(rs, colName);
}