SetBinaryStream

Hello,
I'm having trouble with the java.sql.PreparedStatement.setBinaryStream() method with oracle 10g. While it used to work well before in a PostgreSQL database, it does not save data if its size is more than 2k. I'm using the latest jdbc thin driver for 10g. The frustrating part is that there are no error messages returned and all the other non-blob column updates are saved except for the blob column.

I got the latest drivers for Oracle 10g and they seem to have solved the problem. I was however, working with a 10g driver and 10g database, so I'm not sure if this will work for earlier versions of Oracle DB. At first it didnt work but that was because I only copied the ojdbc14.jar into my servlet's WEB-INF/lib directory (although it works for other JDBC drivers) instead of specifying it as part of the classpath.

Similar Messages

  • AbstractMethodError while calling PreparedStatement.setBinaryStream()

    I am getting AbstractMethodError while calling PreparedStatement.setBinaryStream(int, InputStream) for a BLOB column
    I am using Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit
    JDBC Driver ojdbc6.jar (downloaded from oracle website corresponding to 11.2.0.2 version)
    JDK 6
    I understand this error is due to my code calling abstract method which is not available in JDBC 3.x and it requires JDBC 4.0
    But I am not able to find any traces of usage of earlier version of driver.
    Debugging steps performed with results are as below
    1) I enabled -verbose:class VM argument that outputs all the classes loaded along with jar from which it loads. Everywhere i see ojdbc6.jar (No reference to older or any other jdbc driver jar file)
    2) Below is code segment and its output
    Connection con = getConnection(); // get connection
    DatabaseMetaData d= con.getMetaData();
    d.getDatabaseProductName(); // output: Oracle
    d.getDatabaseProductVersion(); // output: Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    d.getDatabaseMajorVersion(); // output: 11
    d.getDatabaseMinorVersion(); // output: 2
    d.getDriverName(); // output: Oracle JDBC driver
    d.getDriverVersion(); // output: 11.2.0.2.0
    d.getDriverMajorVersion(); // output: 11
    d.getDriverMinorVersion(); // output: 2
    d.supportsGetGeneratedKeys(); // output: true
    3) I updated code (its third party component, so not suppose to update :( )
    Added third argument whick works fine (it means at runtime it is using older jdbc driver???)
    PreparedStatement.setBinaryStream(int, InputStream, (int)length
    Please let me know if i am missing anything here... how can i solve this issue?
    Thanks!

    From my initial post
    I am getting AbstractMethodError while calling PreparedStatement.setBinaryStream(int, InputStream) for a BLOB column
    3) I updated code (its third party component, so not suppose to update )
    Added third argument whick works fine (it means at runtime it is using older jdbc driver???)(3) will not work if correct ojdbc6.jar is used. Because third argument is int and not long. long will work with ojdbc6 but will not work with older version.
    I am using third party component and they are using - PreparedStatement.setBinaryStream(int, InputStream)
    It should work with JDK 6, Oracle 11g and ojdbc6.jar driver.
    I am sure its simple classpath issue or some configuration mismatch - just couldn't see it right now.
    I will probably create new workspace / or test on other system now
    Thanks!

  • Java.sql.Blob method setBinaryStream?

    Hi,
    I've been trying to use the java.sql.Blob methods instead of the "Oracle Extensions" so that people w/o Oracle (using MySQL etc.) can still use my code.
    Problem: trying to get the OutputStream to write to the Blob. As of JDK1.4, java.sql.Blob has a method to do this, setBinaryStream. Unfortunately, calling this in Oracle JDBC (tried it in both thin and OCI version) throws an SQLException (Unsupported feature).
    Sample code:
    //Assume we already have a connection to the database, over either OCI or thin.
    //Assume a Statement stmt created from the connection.
    //Assume a table BlobTable with 2 fields : id (number) and data (blob).
    public void uploadBlob(byte [] theBytes){
         try{
         stmt.executeUpdate("INSERT INTO BlobTable (id, data) VALUES (1,empty_blob())");
         ResultSet rs = stmt.executeQuery("SELECT data FROM BlobTable WHERE id=1 FOR UPDATE");
         if (rs.next()){
    java.sql.Blob blob=rs.getBlob(1);
         OutputStream out=blob.setBinaryStream(0);
         //Next line never printed - error thrown.
         System.out.println("Got Stream");
         catch(Exception e){e.printStackTrace();}
    //End code
    Am I doing something wrong? Or is there simply no way to write to a Blob without using the extensions?
    None of the docs (examples, guides, etc) make any mention of this, although the JDBC dev guide does mention that the similar method in PreparedStmt only works over OCI.
    Thanks,
    Dan

    Hi lancea,
    It's been a while since this thread was active, but I have a related question.
    Is there a comprehensive list of changes between JDBC 3 and JDBC 4 that makes application not work any more, such as this setBinaryStream issue or the CallableStatement/Named parameters issue that we stumbled upon. We would like to address these issues proactively and not find out about them in production, since we're upgrading from jdk1.4 to jdk6. Oracle has provided us with their changes regarding database versions, but have been less forthcoming with JDBC spec version changes.
    Thanks in advance,
    Thomas Auzinger

  • Problem with inserting two BLOBs into a table using setBinaryStream

    DBMS 9.2.0.1.0, Oracle JDBC driver 10.1.0.2.0
    The following code insert in one INSERT two BLOBs
    into two columns using PreparedStatement.setBinaryStream(). When the size of the of at least one blob exceeds
    some limit (? 2k, 4k ?), the values are swapped and
    inserted into wrong columns.
    Please, is this a problem in JDBC driver?
    ====================================================
    import java.io.ByteArrayInputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import java.sql.Statement;
    * Test - two BLOBs swapped problem.
    * If size of the blob is larger that some treshold, they are swapped in the database.
    public class BlobSwapTest {
    private static Connection getConnection() throws SQLException {
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    } catch (ClassNotFoundException cnfe) {
    throw new SQLException("ClassNotFoundException: " + cnfe.getMessage());
    return DriverManager.getConnection("jdbc:oracle:thin:@//HOST:1521/DB", "USER", "PSWD");
    private static void createTable() throws SQLException {
    Connection conn = getConnection();
    Statement stmt = null;
    try {
    stmt = conn.createStatement();
    try {
    stmt.execute("DROP TABLE BlobTest2");
    } catch (SQLException e) {
    System.err.println("Table BlobTest2 was not deleted: " + e.getMessage());
    stmt.execute(
    "CREATE TABLE BlobTest2 ("
    + " pk VARCHAR(512), "
    + " blob BLOB, "
    + " blobB BLOB, "
    + " PRIMARY KEY (pk)"
    + ")"
    } finally {
    try {
    if (stmt != null) stmt.close();
    } finally {
    conn.close();
    public static void main(String[] args) throws SQLException {
    createTable();
    Connection conn = getConnection();
    PreparedStatement pstmt = null;
    try {
    conn.setAutoCommit(false);
    pstmt = conn.prepareStatement("INSERT INTO BlobTest2 VALUES (?,?,?)");
    final int size = 5000; // change the value to 500 and the test is OK
    byte[] buf = new byte[size];
    byte[] buf2 = new byte[size];
    for (int i = 0; i < size; i++) {
    buf = 66;
    buf2 = 88;
    pstmt.setString(1, "PK value");
    pstmt.setBinaryStream(2, new ByteArrayInputStream(buf), size);
    pstmt.setBinaryStream(3, new ByteArrayInputStream(buf2), size);
    pstmt.executeUpdate();
    conn.commit();
    } finally {
    if (pstmt != null) pstmt.close();
    conn.close();
    ====================================================

    See my response in the JVM forum.

  • Oracle.sql.BLOB.setBinaryStream() throws UnsupportedFeatureException

    Does anyone know why oracle.sql.BLOB.setBinaryStream(long pos) throws an UnsupportedFeatureException? It seesm to me that if the method were rewritten as:
    public OutputStream setBinaryStream(long pos) throws SQLException {
         return getDBAccess().newOutputStream(this, getBufferSize(), pos);
    ... then there would be no reason to throw an exception.
    Ideas?
    - David

    Hi Dave,
    I ran into this when I did rs.getBlob(1).setBinaryStream(0) using the ojdbc1_4 driver (without casting to oracle.sql.BLOB). Someone pointed out that I needed to select the BLOB column FOR UPDATE. I did this and now I am getting ORA-01002: fetch out of sequence.
    Not sure if I have helped you any...still digging around for the meaning of ORA-01002
    Raj

  • What exactly do I have to put in setBinaryStream(long pos)?

    I'm so confused.
    Someone put 0L and someone put 1L.
    Well oracle jdbc says 0L, but..I'm still confused....
    Anybody?

    Oooooops.
    I'm so sorry, I'm talkin' about the metohd setBinaryStream(long pos) of java.sql.Blob not XXXStatements or ResultSet.
    Sorry.
    I know the parameter index start with 1 in statements and resultset.
    But it's not sure when it comes to say, Blob.setBinaryStream(long pos).
    I actually tried with both 0L and 1L,
    And the most interest thing is both cases seem to be ok.
    When I put 2L, there is an empty byte placed on the first stream.
    When I put 3L, there are two empty bytes placed on the first stream.
    And so on.
    I think (I just think) both 0L and 1L seem to be ok for the first stream.
    I coudn't find any clue from jdbc spec through oracle jdbc
    ANYbody has ANY concrete solution?

  • Blob setBytes and setBinaryStream Clarification Needed

    I'm writing a JDBC driver for SQL Server and working on the Blob implementation details.
    One thing that is not clear in the JDBC spec to me at least is the behavior of the call to setBytes and to setBinaryStream on a Blob.
    Say for a simple example I have a Blob with 5 bytes in it ->
    1 2 3 4 5
    AA BB CC DD EE
    So in the database these 5 bytes are stored. I open a Blob on this field.
    Then I call setBytes with offset of 3 and write bytes 11 22 33 44
    Do I get this ->
    1 2 3 4 5 6
    AA BB 11 22 33 44 <- Writes over data, also past end of Blob.
    Or this?
    1 2 3 4 5
    AA BB 11 22 33 <- Writes over data, but not past end of Blob.
    Or this?
    1 2 3 4 5 6 7 8 9
    AA BB 11 22 33 44 CC DD EE <- Inserts data at offset, pushes existing data to right.
    So in other words, does setBytes insert data at the insertion point, or start overwriting data at the insertion point? Also, does it allow you to keep writing the data in the backend Blob past the end of the Blob?
    Same goes for setBinaryStream. The API spec is not clear about the desired behavior.
    Thanks for any clues!
    Matt

    Well... looking at the API...
    public void setBytes(int parameterIndex, byte[] x)
        throws SQLExceptionSets the designated parameter to the given Java array of bytes.
    The driver converts this to an SQL VARBINARY or LONGVARBINARY
    (depending on the argument's size relative to the driver's limits
    on VARBINARY values) when it sends it to the database.
    public void setBinaryStream(int parameterIndex, InputStream x,int length)
        throws SQLExceptionSets the designated parameter to the given input stream, which will
    have the specified number of bytes. When a very large binary value
    is input to a LONGVARBINARY parameter, it may be more practical to send
    it via a java.io.InputStream object. The data will be read from the
    stream as needed until end-of-file is reached.
    It appears that setBytes() you pass in an entire in-memory array
    of bytes, whereas setBinaryStream() allows you to pass in an
    InputStream that contains the bytes.

  • When to use setBytes() and setBinaryStream()

    Hi,
    I am using oracle thin driver to insert a image (blob type) into database.
    Which method of PreparedStatement interface should I use to insert data,
    setBytes() or SetBinaryStream().
    My understanding is BinaryStream also sends data in form of bytes.
    Then what is the difference between these two method ?
    Please let me know.
    Thanks,
    -Amol

    Well... looking at the API...
    public void setBytes(int parameterIndex, byte[] x)
        throws SQLExceptionSets the designated parameter to the given Java array of bytes.
    The driver converts this to an SQL VARBINARY or LONGVARBINARY
    (depending on the argument's size relative to the driver's limits
    on VARBINARY values) when it sends it to the database.
    public void setBinaryStream(int parameterIndex, InputStream x,int length)
        throws SQLExceptionSets the designated parameter to the given input stream, which will
    have the specified number of bytes. When a very large binary value
    is input to a LONGVARBINARY parameter, it may be more practical to send
    it via a java.io.InputStream object. The data will be read from the
    stream as needed until end-of-file is reached.
    It appears that setBytes() you pass in an entire in-memory array
    of bytes, whereas setBinaryStream() allows you to pass in an
    InputStream that contains the bytes.

  • RegisterOutParameter - setBinaryStream - Problems inserting Blob - setRAW

    As posted in metalink (was: "Problems inserting BLOB/InputStream with ojdbc14.jar for 10g - Data size bigger than max size for this type"):
    Using setBinaryStream for large Blobs works as long as I don't register outParameters.
    Query that works: "INSERT INTO blobtest (attachment_id,name,data) VALUES(blobtest_SEQ.nextval,?,?)";
    Query that fails = "BEGIN INSERT INTO blobtest (attachment_id,name,data) VALUES( blobtest_SEQ.nextval,?,?) RETURN attachment_id INTO ? ; END;"
    The necessary tables were created by hand:
    CREATE TABLE blobtest ( NAME CHAR(255), data BLOB, attachment_id NUMBER(38))
    And
    CREATE SEQUENCE TBL_ATTACHMENT_SEQ
    The output was: <<user: SEE
    pw: QD
    instantiating oracle driver
    query: INSERT INTO blobtest (attachment_id,name,data) VALUES(TBL_ATTACHMENT_SEQ.nextval,?,?)
    uploaded no Return Parameter blob of size: 256809
    query: BEGIN INSERT INTO blobtest (attachment_id,name,data) VALUES(TBL_ATTACHMENT_SEQ.nextval,?,?) RETURN attachment_id INTO ? ; END;
    java.sql.SQLException: Datengr÷&#9600;e gr÷&#9600;er als max. Gr÷&#9600;e f³r diesen Typ: 256809
    at
    oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java
    :125)
    at
    oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java
    :162)
    at
    oracle.jdbc.driver.OraclePreparedStatement.setRAW(OraclePreparedState
    ment.java:5342)
    at
    oracle.jdbc.driver.OraclePreparedStatement.setBinaryStreamInternal(Or
    aclePreparedStatement.java:6885)
    at
    oracle.jdbc.driver.OracleCallableStatement.setBinaryStream(OracleCall
    ableStatement.java:4489)
    at BlobTest.writeBlob(BlobTest.java:161)
    at BlobTest.testBlob(BlobTest.java:118)
    at BlobTest.main(BlobTest.java:92)
    error: Datengr÷&#9600;e gr÷&#9600;er als max. Gr÷&#9600;e f³r diesen Typ:
    256809>>
    here the java test case:
    * Created on 25.08.2004 $Id: BlobTest.java,v 1.4 2005/04/22 11:21:11 hauser Exp $
    * as posted in metalink jdbc forum 050405 and responses by
    * [email protected]
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.Driver;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.Types;
    public class BlobTest {
    private static String FILE_NAME = "c:/temp/veryLargeFile.pdf";
    public BlobTest() {
    final static int ORACLE = 1;
    final static int MYSQL = 2;
    private String jdbcUrl = "jdbc:mysql://localhost/test?user=monty&password=greatsqldb";
    private int dbType = ORACLE;
    private Driver driver = null;
    private String user = "";
    private String pw = "";
    public static String SCHEME = "";
    public static void main(String[] args) {
    BlobTest bt = new BlobTest();
    if (args[0] != null) {
    System.out.println("dbType: " + args[0]);
    if (args[0].toLowerCase().indexOf("oracle") != -1) {
    bt.dbType = ORACLE;
    if (args[0].toLowerCase().indexOf("mysql") != -1) {
    bt.dbType = MYSQL;
    } else {
    System.out.println("not yet supported db type: " + args[0]);
    System.exit(99);
    if (args[1] != null) {
    System.out.println("jdbcUrl: " + args[1]);
    if (args[1].trim().length() != 0) {
    bt.jdbcUrl = args[1].trim();
    } else {
    System.out.println("not yet supported jdbcUrl : " + args[1]);
    System.exit(99);
    if (args.length > 2 && args[2] != null) {
    System.out.println("user: " + args[2]);
    if (args[2].trim().length() != 0) {
    bt.user = args[2].trim();
    } else {
    System.out.println("invalid user: " + args[2]);
    System.exit(99);
    if (args.length > 3 && args[3] != null) {
    System.out.println("pw: " + args[3].substring(0, 2));
    if (args[3].trim().length() != 0) {
    bt.pw = args[3].trim();
    } else {
    System.out.println("invalid filename: " + args[3]);
    System.exit(99);
    if (args.length > 4 && args[4] != null) {
    System.out.println("filename: " + args[4]);
    if (args[4].trim().length() != 0) {
    FILE_NAME = args[4].trim();
    } else {
    System.out.println("invalid filename: " + args[4]);
    System.exit(99);
    bt.setUp();
    bt.testBlob();
    public void setUp() {
    try {
    if (this.dbType == ORACLE) {
    System.out.println("instantiating oracle driver ");
    this.driver = (Driver) Class.forName(
    "oracle.jdbc.driver.OracleDriver").newInstance();
    } else {
    this.driver = (Driver) Class.forName("com.mysql.jdbc.Driver")
    .newInstance();
    if (this.driver == null) {
    System.out.println("oracle driver is null");
    System.exit(88);
    DriverManager.registerDriver(this.driver);
    } catch (Exception e) {
    e.printStackTrace();
    System.out.println("error: " + e.getMessage());
    public void testBlob() {
    try {
    this.writeBlob();
    } catch (Exception e) {
    e.printStackTrace();
    System.out.println("error: " + e.getMessage());
    * testfunction
    private void writeBlob() throws Exception {
    Connection conn = null;
    PreparedStatement pStmt = null;
    CallableStatement cStmt, cStmt2 = null;
    InputStream in = null;
    try {
    File file = new File(BlobTest.FILE_NAME);
    in = new FileInputStream(file);
    conn = DriverManager.getConnection("jdbc:" + this.jdbcUrl,
    this.user, this.pw);
    conn.setAutoCommit(false);
    String queryWorks = "INSERT INTO " + SCHEME
    + "blobtest (attachment_id,name,data) VALUES(" + SCHEME
    + "TBL_ATTACHMENT_SEQ.nextval,?,?)";
    cStmt = conn.prepareCall(queryWorks);
    System.out.println("query: " + queryWorks);
    cStmt.setString(1, file.getAbsolutePath());
    in = new FileInputStream(file);
    cStmt.setBinaryStream(2, in, (int) file.length());
    cStmt.execute();
    System.out.println("uploaded no Return Parameter blob of size: "
    + file.length());
    conn.commit();
    String queryFails = "BEGIN INSERT INTO " + SCHEME
    + "blobtest (attachment_id,name,data) VALUES(" + SCHEME
    + "TBL_ATTACHMENT_SEQ.nextval,?,?)"
    + " RETURN attachment_id INTO ? ; END;";
    cStmt2 = conn.prepareCall(queryFails);
    System.out.println("query: " + queryFails);
    cStmt2.setString(1, file.getAbsolutePath());
    in = new FileInputStream(file);
    cStmt2.setBinaryStream(2, in, (int) file.length());
    cStmt2.registerOutParameter(3, Types.INTEGER);
    cStmt2.execute();
    System.out.println("uploaded blob of size: " + file.length()
    + " - id: " + cStmt2.getInt(3));
    conn.commit();
    } catch (Exception e) {
    e.printStackTrace();
    System.out.println("error: " + e.getMessage() + "\nname: "
    + BlobTest.FILE_NAME);
    if (conn != null) {
    try {
    conn.rollback();
    } catch (Exception e1) {
    throw e;
    } finally {
    if (in != null) {
    try {
    in.close();
    } catch (Exception e) {
    if (pStmt != null) {
    try {
    pStmt.close();
    } catch (Exception e) {
    if (conn != null) {
    try {
    conn.close();
    } catch (Exception e) {
    and the batch file I use to start:
    @setlocal
    @echo off
    rem $Id: runBlobTest.bat,v 1.2 2005/04/21 15:06:22 hauser Exp $
    set classpath=../WEB-INF/classes;../WEB-INF/lib/ojdbc14.jar;
    echo JAVA_HOME: %JAVA_HOME%
    set JAVA_HOME=C:\PROGRA~1\Java\j2re1.4.1_02\
    echo classpath: %classpath%
    set javaCmd=C:\PROGRA~1\Java\j2re1.4.1_02\bin\java
    %javaCmd% -version
    %javaCmd% BlobTest "oracle" "oracle:thin://@ORADB.yourdomain.COM:1521:t300" "username" "password" "C:\Temp\veryLargeFile.pdf"
    endlocal

    Apparently, this is partially known - with a different stacktrace though:
    <<From: Oracle, Anupama Srinivasan 25-Apr-05 07:15
    Can you please check on Bug:4083226?
    Using the RETURNING Clause is not supported with JDBC. You could embed the statement in PL/SQL Block as in Metalink Note 124268.1 - JDBC Support for DML Returning Clause.
    The Enhancement Request filed on this issue is being considered for Release 10.2
    >>
    And my answer to it.
    Using the RETURNING Clause is not supported with JDBC.This is strange, with just "emptyblob()", it DOES work.
    I guess, our work-around that hopefully is more portable than embedding a "PL/SQL Block" will be to
    1) create the record with an empty blob,
    2) update the blob in a second statement (now, a RETURNING statement is no longer needed)

  • OraclePreparedStatement and setBinaryStream

    Im getting a java.lang.StackOverflowError using the setBinaryStream method on OraclePreparedStatement. Anyone run across this before? Not sure what Im doing wrong. The serialized size of the object Im trying to send to the setBinaryStream method is around 8.2k
    Database version: Oracle8i Enterprise Edition Release 8.1.7.4.0 - Production
    Using the Oracle (XA) JDBC driver (10.1.0.2.0)
    The problem is happening using IBM WSAD 5.1. Any ideas what Im doing wrong? Ive been fighting this at long longer than I care to admit.
    java.lang.StackOverflowError
         at java.lang.Throwable.(Throwable.java)
         at java.lang.Throwable.(Throwable.java)
         at java.lang.StackOverflowError.(StackOverflowError.java:51)
         at oracle.jdbc.driver.OraclePreparedStatement.setRAW(OraclePreparedStatement.java)
         at oracle.jdbc.driver.OraclePreparedStatement.setBinaryStreamInternal(OraclePreparedStatement.java)
         at oracle.jdbc.driver.OraclePreparedStatement.setRAW(OraclePreparedStatement.java)
         at oracle.jdbc.driver.OraclePreparedStatement.setBinaryStreamInternal(OraclePreparedStatement.java)
         at oracle.jdbc.driver.OraclePreparedStatement.setRAW(OraclePreparedStatement.java)
         at oracle.jdbc.driver.OraclePreparedStatement.setBinaryStreamInternal(OraclePreparedStatement.java)
    <snipped about 5 pages of of this
         at oracle.jdbc.driver.OraclePreparedStatement.setRAW(OraclePreparedStatement.java)
         at oracle.jdbc.driver.OraclePreparedStatement.setBinaryStreamInternal(OraclePreparedStatement.java)
         at oracle.jdbc.driver.OraclePreparedStatement.setRAW(OraclePreparedStatement.java)
         at oracle.jdbc.driver.OraclePreparedStatement.setBinaryStreamInternal(OraclePreparedStatement.java)
         at oracle.jdbc.driver.OraclePreparedStatement.setRAW(OraclePreparedStatement.java)
         at oracle.jdbc.driver.OraclePreparedStatement.setBinaryStreamInternal(OraclePreparedStatement.java)
         at oracle.jdbc.driver.OraclePreparedStatement.setBinaryStream(OraclePreparedStatement.java:6847)
         at com.ibm.ws.rsadapter.jdbc.WSJdbcPreparedStatement.setBinaryStream(WSJdbcPreparedStatement.java:838)
    <snipped>

    Code snippet that might help: Thanks in advance for any help:
    Method with the problem contains this snippet of code:
    byte[] bytesValue = serialize(value, key);
    ByteArrayInputStream stream = new ByteArrayInputStream (bytesValue);
    if (bytesValue != null)
    //The following throws the java.lang.StackOverflowError
    statement.setBinaryStream(
    3,
    stream,
    bytesValue.length);
    else
    statement.setBytes(3, null);
    serialize (Serializable object, String key) method:
    if (object == null)
    return null;
    ObjectOutputStream stream = null;
    ByteArrayOutputStream byteStream = null;
    try
    byteStream = new ByteArrayOutputStream(512);
    stream = new ObjectOutputStream(byteStream);
    // Serialize the object.
    stream.writeObject(object);
    return byteStream.toByteArray();
    catch (IOException e)
    Attributes tokens = new Attributes();
    tokens.set(OBJECT_KEY_STRING, key);
    throw new ObjectSerializationException(tokens, e);
    finally
    { // Ensure that the output stream is explicitly closed regardless of the exit path
    // of this method.
    try
    if (byteStream != null)
    byteStream.close();
    if (stream != null)
    stream.close();
    catch (IOException e)
    Attributes tokens = new Attributes();
    tokens.set(OBJECT_KEY_STRING, key);
    throw new ObjectSerializationException(tokens, e);
    }

  • SetBinaryStream Error with oracle

    I want to store picture into Oracle9i Database,so I use
    import java.io.*;
    import java.util.*;
    import java.sql.*;
    import javax.sql.*;
    import javax.naming.*;
    public class test{
       public static void main(String args[]){
        Statement stmt=null;
        Connection conn=null;
        try{
             File file = new File("myimage.gif");
             FileInputStream fis = new FileInputStream(file); 
             Class.forName("oracle.jdbc.driver.OracleDriver");
             conn = DriverManager.getConnection("jdbc:oracle:thin:@test:1521:test","scott","tiger"); 
             PreparedStatement ps = conn.prepareStatement("insert into test values (?,?)");
             ps.setString(1,file.getName());
             ps.setBinaryStream(2,fis,file.length());
             ps.executeUpdate();
             ps.close();
             fis.close();
          catch(Exception err){
           err.printStackTrace();
        finally{
         try{                    
           conn.close();
         catch(SQLException err){
           err.printStackTrace();
    }My test table is follows:
    AA NOT NULL VARCHAR2(20)
    BB BLOB
    when I run above code,it raise errors:
    Exception in thread "main" java.lang.AbstractMethodError: oracle.jdbc.driver.Ora
    clePreparedStatement.setBinaryStream(ILjava/io/InputStream;J)V
    at a.test.main(test.java:18)
    I am puzzled with it! Anyone could tell me how to correct it?

    Hi,
    but I checked my java version following this steps:
    1a - In Windows, Classic View, open the Control Panel and then double-click the Java icon.
    1b - In Category View, select the Other Control Panel Options, and then click the Java icon.
    2- In the Java Control Panel window click the Java tab, and then click View.
    3 - In the Platform column, make sure that version 1.5 or higher exists and that it is enabled.
    To get the latest version of Java Runtime Environment, navigate to: http://www.java.com
    And my Java Version is 1.6
    =/

  • Why is there a length attribute in setBinaryStream()

    Hello,
    I am wondering why you have to supply a length attribute in method setBinaryStream(). Normally you do not know the size of the data stream, especially if you create it by marshalling java objects in a separate Thread. For such a case I would like to use the possibility to work with streams when writing to the database. But not knowing the length of the data is a problem. InputStream.available() is not a solution, as it only gets the number of bytes that can be read non-blocking.
    The only workaround I can think of is writing in a temp-file, getting its size and creating a new InputStream out of it to write to the database.
    Do I miss something here? I think there should be a more elegant solution...
    Thanks,
    Daniel

    I'm using this API with the Microsoft SQL Server 2005 driver (on a SQL Server 2000 database).
    Microsoft's implementation of this interface (documented here: http://msdn2.microsoft.com/en-us/library/ms378983.aspx) allows -1 to be supplied as the length parameter and it will read to EOF.
    So this code works for me:
    PreparedStatement pstmt = con.prepareStatement("INSERT INTO Files ...");
    pstmt.setBinaryStream(5, inputStream, (int)size);
    It looks like Sun have updated the documentation of this API with JDK 5 also:
    http://java.sun.com/j2se/1.5.0/docs/api/java/sql/PreparedStatement.html#setBinaryStream(int,%20java.io.InputStream,%20int)
    To quote: "... When a very large binary value is input to a LONGVARBINARY parameter, it may be more practical to send it via a java.io.InputStream object. The data will be read from the stream as needed until end-of-file is reached."
    After investigating this lead, I have found this code works also:
    pstmt.setObject(5, inputStream);
    Perhaps the length parameter was included in the setBinaryStream method in the API because some databases need to allocate space in advance of saving the stream. For those that don't need to allocate space in advance, their drivers might typically accept -1 as the length, and read the stream to the end of file. It's possible that supplying it when it is available might allow the database to allocate space in advance, which might improve performance (this is speculation).
    It has taken me a long time to sort out this issue! The main problem was that older API documentation failed mention that it was possible to stream without specifying the length. To anyone in a similar situation - read the JDK 5 API documentation and documentation on your driver's implementation of PreparedStatement.
    In summary - I can confirm you don't need to specify the length of a stream for MS SQL Server databases.

  • Error while iserting a image in DB!!!!!

    Hello guys,
    I want to insert an image in the DB(MySql). I receive a compiling error when i try to insert an image.
    I tried to find in the forums.. but i could not find it..
    here is my code..
    public void insertImage(String name, String path){
              try{
         ImageIcon icon = new ImageIcon(path);
         Image image = icon.getImage();
            BufferedImage bImage = new BufferedImage(image.getWidth(null),image.getHeight(null),BufferedImage.TYPE_INT_RGB);
            Graphics bg = bImage.getGraphics();
            bg.drawImage(image,0,0,null);
            bg.dispose();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(bImage,"jpeg",out);
            byte[] buf = out.toByteArray();
            ByteArrayInputStream inStream = new ByteArrayInputStream(buf);
              try {
              String query = "insert  into instimage(Name, Image) values ('"+name+"',?)";
              PreparedStatement ps = conn.prepareStatement(query);
              ps.setBinaryStream(1,inStream,inStream.available());
              int count = ps.executeUpdate(query);
              }catch (SQLException e) {
                   e.printStackTrace();
              }     catch (Exception e) {
                   e.printStackTrace();
         The error is
    com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax;
    check the manual that corresponds to your MySQL server version for the right syntax to use near '?)' at line 1I would be grateful, if u guys help me out!!
    Thanks
    Edited by: frenchiee on Aug 27, 2008 8:16 AM

    Your query looks like valid. But only if the name variable has good value. If name has value "name with apostrophe'", your code will fail. Try
    String query = "insert into instimage(Name, Image) values (?,?)";
    PreparedStatement ps = conn.prepareStatement(query);
    ps.setString(1,name);
    ps.setBinaryStream(2,inStream,inStream.available());

  • Error while trying to store PDF in Oracle's BLOB field

    Hi folks!
    I'm having problems while trying to store PDF file in a BLOB field of an Oracle table
    This is the message code:
    Exception in thread "main" java.sql.SQLException: Data size bigger than max size for this type: 169894
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
    at oracle.jdbc.ttc7.TTCItem.setArrayData(TTCItem.java:95)
    at oracle.jdbc.dbaccess.DBDataSetImpl.setBytesBindItem(DBDataSetImpl.java:2414)
    at oracle.jdbc.driver.OraclePreparedStatement.setItem(OraclePreparedStatement.java:1134)
    at oracle.jdbc.driver.OraclePreparedStatement.setBytes(OraclePreparedStatement.java:2170)
    at vgoactualizacion.Main.main(Main.java:84)     
    This is the piece of code i'm using:
    Assuming conn = conection to Oracle 10g Database ( it's working )
    String miProcedimientoAlmacenado = "{ call package_name.update_client(?,?, ?) }";
    CallableStatement miComando = conn.prepareCall(miProcedimientoAlmacenado);
    miComando.setString(1,miClienteID ); //first parameter : IN
                   //second parameter : IN
    File miPDF = new File(pathPDF + "//" + miClienteID + ".pdf");
    byte[] bodyIn = readFully(miPDF); //readFully procedure is shown below
    miComando.setBytes(2, bodyIn); //THIS IS THE LINE WHERE THE ERROR IS PRODUCED
              //3rd parameter: OUT
    miComando.registerOutParameter(3, java.sql.Types.VARCHAR);
    miComando.execute();
    private static byte[] readFully(File miPDF) throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream(miPDF);
    byte[] tmp = new byte[1024];
    byte[] data = null;
    int sz, len = 0;
    while ((sz = fis.read(tmp)) != -1) {
    if (data == null) {
    len = sz;
    data = tmp;
    } else {
    byte[] narr;
    int nlen;
    nlen = len + sz;
    narr = new byte[nlen];
    System.arraycopy(data, 0, narr, 0, len);
    System.arraycopy(tmp, 0, narr, len, sz);
    data = narr;
    len = nlen;
    if (len != data.length) {
    byte[] narr = new byte[len];
    System.arraycopy(data, 0, narr, 0, len);
    data = narr;
    return data;
    }//fin readFully
    This approach indicates that the PDF file is converted into an array of bytes, then is stored as binary in the BLOB field.
    Thanx in advance, and looking forward for your comments.

    You will probably need to use the setBinaryStream() method instead of setBytes().

  • Setting a null(empty) binary stream in a PreparedStatement

    How can I bind a null binary stream into a PreparedStatement?
    In the following, if pMap is null how do I bind it? If I try to serialize a null pMap I get and error that not all columns bound.
    if(pMap == null)
    else
    byte[] _bytes = SerializeUtility.serializeObject(pMap);
    pStatement.setBinaryStream(pColCount, new ByteArrayInputStream(_bytes), _bytes.length);
    Thanks,
    David

    I was too close to the monitor, couldn't see the big picture ! :-) Now it works.
    Although, I still get that Websphere error:
    7c7fc721 SharedPool I J2CA0086W: Shareable connection MCWrapper id 31c73d Managed connection comm.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl@2e55c73d State:STATE_TRAN_WRAPPER_INUSE from resource jdbc/ds was used within a local transaction containment boundary.
    It use to work fine, no errors.
    Any ideeas??
    mihut

Maybe you are looking for

  • HT201303 im trying to recover my apple ID

    im trying to recover my apple ID

  • Calls failing to connect due to "Internal Error"

    I have been having issues, with increasing frequency, with Skype on my Mac as well as iPhone. Now EVERY time I try to call a phone number it gives the notification of "Call ended - internal error". What the **bleep**?

  • Controlling interchange id in UNB

    We have a situation where we send EDIFACT D96A INVOIC messages from BPEL to B2B for transport with SFTP to different external parties. The problem is that both the host and some of the external partners represent multiple companies and use multiple i

  • Adobe Flash Player update 11 gave me a virus

    The newest adobe flash player update gave my computer a virus that required me doing a system restore and completely removing adobe flash player from my system. It was sending spam emails in different languages and spam videos. It was able to slip th

  • Tile based help

    Hi. I'm pretty new to actionscript and especially object oriented programming. I'm trying to create simple puzzle game in which three sets of colored pieces move on a board like knights in chess; except when the pieces are on black sqares, in which c