BLOB to byte[] mapping

Hi,
In my table, one of the columns is of type BLOB. When I generate Java objects out of the database, the type of this column becomes java.sql.Blob. This seems to be the default mapping. I want it to be of type byte[].
How do I configure Toplink Workbench to map it always as byte[]?

Either value in the object model is valid. You can modify the generated class to hold a byte[].
If you are using the Oracle thin JDBC driver you should map the byte[] attribute as a TypeConversionMapping and select the type to be java.sql.BLOB.
Doug

Similar Messages

  • POJO - Pictures, Blob ot byte[]

    Hi All,
    the POJO Reporting works fine but
    How can i include a picture into my Report ??
    If i move my object (with a Blob and byte[]) into myReport.rpt the Blob and the byte[] does not become available for reporting.
    What is wrong ??
    Thanks for Your help
    René
    My Object:
    public class RhuPlakatData {
    private String text11;
    private Blob blob1;
    private byte[] bytes;
    public byte[] getBytes() {
    return bytes;
    public void setBytes(byte[] bytes) {
    this.bytes = bytes;
    public String getText11() {
    return text11;
    public void setText11(String text11) {
    this.text11 = text11;
    public Blob getBlob1() {
    return blob1;
    public void setBlob1(Blob blob1) {
    this.blob1 = blob1;

    Hi James
    Unfortunately, I found no solution.
    Did You found a solution??
    Thanks for Your help
    Greetings
    René

  • Blob to byte[] detach failure

    Hi,
    I'm unable to detach a byte array using Kodo 3.3.4 and PostgreSQL 8.0. The
    byte array in the detached object is always empty despite there being
    bytes in the database table for the correspond column/row. Other fields
    are detached correctly.
    In my JDO file -
    <field name="image">
    <!-- Map image to BLOB field -->
    <extension vendor-name="kodo" key="jdbc-field-map-name" value="blob">
    <extension vendor-name="kodo" key="column" value="image"/>
    </extension>
    </field>
    This correctly creates a column of named 'image' of type 'bytea' in the
    table.
    This issue isn't listed in the know issues for PostgresQL - can anybody
    else confirm they have this working with this database? I see there was a
    similar problem with mySQL posted here, but then that issue wasn't
    documented either.
    Thanks,
    Andy.

    byte[] fields aren't in the default fetch group by default, and
    detachment only occurs on fields in the DFG. Both of these options
    (whether the field is in the DFG, and whether detachment works on DFG
    fields or uses some other criteria), are configurable. I assume you
    know how to control DFG settings; the documentation on detachment is here:
    http://www.solarmetric.com/Software/Documentation/latest/docs/ref_guide_remote.html#ref_guide_detach_graph

  • Exception getting blob to byte[]

    Hy guys,
    I 've a problem with my java application.
    I use hibernate to interact with a derby database.
    I stored a image into blob field (and no problem).
    When I try to get blob to array of byte I've this exception:
    java.sql.SQLException: You cannot invoke other java.sql.Clob/java.sql.Blob methods after calling the free() method or after the Blob/Clob's transaction has been committed or rolled back.To get blob I did
    Blob cThumnb = ((Allegato) cAllegati.get(i)).getThumb();
    byte[] cPrev = toByteArray(cThumnb);where
    private byte[] toByteArray(Blob fromBlob) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                return toByteArrayImpl(fromBlob, baos);
            catch (SQLException e)
                throw new RuntimeException(e);
            catch (IOException e)
                throw new RuntimeException(e);
            finally
                if (baos != null)
                    try
                        baos.close();
                    catch (IOException ex)
        private byte[] toByteArrayImpl(Blob fromBlob, ByteArrayOutputStream baos)  throws SQLException, IOException
            byte[] buf = new byte[4000];
            InputStream is = fromBlob.getBinaryStream();
            try
                for (;;)
                    int dataSize = is.read(buf);
                    if (dataSize == -1)     break;
                    baos.write(buf, 0, dataSize);
            catch(IOException ex)
                    throw ex;
           finally
                if (is != null)
                    try
                        is.close();
                    catch (IOException ex)
                    return  buf;// baos.toByteArray();
        }Could you help me?
    I set also autocommit to false,
    Thanks,
    Regards

    EJP wrote:
    So could you cite some references that show, in general, that one normally needs to process blobs as streams?The design. The name, which is an acroynm for Binary Large Object. The fact that they have a stream interface, like files and sockets.The idiom for loading does not require nor even recommend that one must process as a stream.
    And most of the time I do not process files nor sockets via streaming methodologies. I load them entirely, then process them.
    Actually for direct socket usage, excluding protocols like FTP, I don't believe I have ever streamed processing because in message based protocols the messages are very small.
    Presumably because the OP has one reference to 'thumb' as in thumbnail view?From the OP's first post: 'I stored a image into blob field'.I see. I have stored images in databases before. Excluding storage of medical media files they were all processed in memory because all were rather small.
    Certainly cases where one does in fact want to read an entire file into memory, before one starts processing it.Can't think of any, but in any case if you are able to process it as a stream you are wasting both time and space by not doing so.If I have any data that is in fact "large" I will keep that in mind. But, for example, I can't see processing a configuration file that consists of a couple hundred bytes via stream processing just because files allow for the possibility that one can process a large file.

  • Map oracle 9 BLOB type

    I am trying to map a BLOB database object to a java object using typeconversion with TopLink version 9.0.4.1 (build 040128).
    How do I map a BLOB database type? I tried to map it to oracle.sql.BLOB object in my class, (private BLOB m_blobField) but I get an error message:
    Local Exception Stack:
    Exception [TOPLINK-3001] (OracleAS TopLink - 10g (9.0.4.1) (Build 040128)): oracle.toplink.exceptions.ConversionException
    Exception Description: The object [[B@1bdc9d8], of class [class [B], could not be converted to [class oracle.sql.BLOB].
         at oracle.toplink.exceptions.ConversionException.couldNotBeConverted(ConversionException.java:35)
         at oracle.toplink.internal.helper.ConversionManager.convertObject(ConversionManager.java:154)
         at oracle.toplink.internal.databaseaccess.DatabasePlatform.convertObject(DatabasePlatform.java:562)
         at oracle.toplink.mappings.DirectToFieldMapping.getAttributeValue(DirectToFieldMapping.java:224)
         at oracle.toplink.mappings.TypeConversionMapping.getAttributeValue(TypeConversionMapping.java:41)
         at oracle.toplink.mappings.DirectToFieldMapping.valueFromRow(DirectToFieldMapping.java:458)
         at oracle.toplink.mappings.DatabaseMapping.readFromRowIntoObject(DatabaseMapping.java:860)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:164)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:322)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildObjectsInto(ObjectBuilder.java:380)
         at oracle.toplink.internal.queryframework.DatabaseQueryMechanism.buildObjectsFromRows(DatabaseQueryMechanism.java:146)
         at oracle.toplink.queryframework.ReadAllQuery.execute(ReadAllQuery.java:425)
         at oracle.toplink.queryframework.DatabaseQuery.execute(DatabaseQuery.java:493)
         at oracle.toplink.queryframework.ReadQuery.execute(ReadQuery.java:111)
         at oracle.toplink.publicinterface.Session.internalExecuteQuery(Session.java:1958)
         at oracle.toplink.publicinterface.Session.executeQuery(Session.java:1086)
         at oracle.toplink.publicinterface.Session.executeQuery(Session.java:1038)
         at oracle.toplink.publicinterface.Session.readAllObjects(Session.java:2372)
         at com.starhometest.Tests.RunTest.testBlob(RunTest.java:158)
         at com.starhometest.Tests.RunTest.main(RunTest.java:59)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at com.intellij.rt.execution.application.AppMain.main(AppMain.java:78)
    Exception in thread "main"
    Trying to map it to the Blob interface also doesn't work.
    Can anyone help?

    BLOB should be mapped to a byte array using TypeConversionMapping with a target type java.sql.Blob. Also Oracle8Platform or Oracle9Platform should be used.
    For more details please see http://www.oracle.com/technology/products/ias/toplink/technical/tips/LOB/index.html

  • Please help, I need to read blob and output in bytes from wwv_flow_files.

    Hi all,
    I am having a requirement to read a blob stored in the oracle table and convert it into bytes. I am loading this table (wwv_flow_files) with APEX.
    The code under page 1 is as follows:
    DECLARE
    z number;
    y varchar2(4000);
    x varchar2(400);
    b blob;
    BEGIN
    select filename,blob_content into x ,b from APEX_APPLICATION_files where name =:P1_FILE_NAME;
    select length(convertBlobToBytes(b)) into z from dual;
    :P1_RESULT := z;
    end;
    Java code is as follows:
    import java.io.*;
    import java.sql.Blob;
    public class convertBlob {
    * @param blob
    * @return
    public static byte[] convertBlobToBytes(Blob blob) {
    if (blob==null) return null;
    try {
    InputStream in = blob.getBinaryStream();
    int len = (int) blob.length(); //read as long
    long pos = 1; //indexing starts from 1
    byte[] bytes = blob.getBytes(pos, len);
    in.close();
    return bytes;
    catch (Exception e) {
    System.out.println(e.getMessage());
    return null;
    PL/SQL wrapper is as follows:
    CREATE OR REPLACE FUNCTION convertBlobToBytes(p1 IN BLOB) RETURN LONG RAW AUTHID CURRENT_USER AS LANGUAGE JAVA NAME 'convertBlob.convertBlobToBytes(java.sql.Blob) return byte[]';
    I loaded this java class and pl/sql wrapper into the database using JDEVELOPER.
    But I am getting the length of the file, as twice the size.
    For example, When I run the program which reads the file returns the length of the file as a byte array, the length is 819.
    When I pass the same file as a blob from apex, to the java program that converts blob to bytes, the length of the file is 1638.
    And hence I am getting wrong results, further in the process.
    Can you please help me? Any help is appreciated.
    rgds,
    Suma.

    The example on this page is showing how to read a blob in portions you determine yourself:
    http://apex.oracle.com/pls/otn/f?p=31517:91
    Denes Kubicek
    http://deneskubicek.blogspot.com/
    http://www.opal-consulting.de/training
    http://apex.oracle.com/pls/otn/f?p=31517:1
    -------------------------------------------------------------------

  • Plesae help- needing to read a blob from db into bytes[]

    Hi all,
    I am having a requirement to read a blob stored in the oracle table and convert it into bytes. I am loading this table (wwv_flow_files) with APEX.
    The code under page 1 is as follows:
    DECLARE
    z number;
    y varchar2(4000);
    x varchar2(400);
    b blob;
    BEGIN
    select filename,blob_content into x ,b from APEX_APPLICATION_files where name =:P1_FILE_NAME;
    select length(convertBlobToBytes(b)) into z from dual;
    :P1_RESULT := z;
    end;
    Java code is as follows:
    import java.io.*;
    import java.sql.Blob;
    public class convertBlob {
    * @param blob
    * @return
    public static byte[] convertBlobToBytes(Blob blob) {
         if (blob==null) return null;
         try {
         InputStream in = blob.getBinaryStream();
         int len = (int) blob.length(); //read as long     
    long pos = 1; //indexing starts from 1
         byte[] bytes = blob.getBytes(pos, len);           
    in.close();
         return bytes;     
    catch (Exception e) {
         System.out.println(e.getMessage());
         return null;
    PL/SQL wrapper is as follows:
    CREATE OR REPLACE FUNCTION convertBlobToBytes(p1 IN BLOB) RETURN LONG RAW AUTHID CURRENT_USER AS LANGUAGE JAVA NAME 'convertBlob.convertBlobToBytes(java.sql.Blob) return byte[]';
    I loaded this java class and pl/sql wrapper into the database using JDEVELOPER.
    But I am getting the length of the file, as twice the size.
    For example, When I run the program which reads the file returns the length of the file as a byte array, the length is 819.
    When I pass the same file as a blob from apex, to the java program that converts blob to bytes, the length of the file is 1638.
    And hence I am getting wrong results, further in the process.
    Can you please help me? Any help is appreciated.
    rgds,
    Suma.

    Hi all,
    Can any of you please help me out?
    rgds,
    Suma.

  • How to upload size 4k file to oracle BLOB field

    hi all, i'm using Oracle 9i, Orcale JDBC thin Driver and ibm websphere to develop a java application.i have used java EJB/CMP to insert images into BLOB field in oracle.
    i used byte[] mapping to BLOB.i did it successfully.
    however, i'm facing another problem. it is that
    when i insert files larger than 4k, there is exception error. it said that the inserted value is too large.
    is that the problem of orcale JDBC?
    is that any solution to solve this restriction?
    it is very urgent, pls help!
    thx a lot

    Hi Lee
    Thanks for ur valuable suggestions. Please give me
    more idea i would really thank to u !Which part is giving you troubles?
    Oh - and change my suggestion to use setBinaryStream to a suggestion to use setAsciiStream, as I missed the part where you said "text file".
    >
    Can anybody tell me anyother way how to solv thid
    problem
    Depending on the size of the text file you could just read the file so you have the contents as a String and use setString (also in the PreparedStatement interface).
    hanks
    Message was edited by:
    MerlinRosina

  • Store pdf in oracle  BLOB  hibernate

    I need to store PDF files in the oracle BLOB using hibernate. I am using the below code and getting a null pointer. Any thoughts?
    Blob blob=null;
    byte [] bFile = (byte[])objVal;
    blob.setBytes(0,bFile); //null pointer here...
    logger.info("EventsDAO- insertDetails- else:--"+((byte[])objVal)+"---blob----"+blob);
    hmForm.put(objKey,blob); Thanks in advance.

    Samples? Are you asking how to make a blob? I have my doubts about the wisdom of using Hibernate if you can't diagnose a NPE unless that was just momentary code snow-blindness, but whatever, it's your problem:
    Either call Hibernate.createBlob(InputStream,long) or just map the field as a byte[] and map it to a Blob type.
    Edited by: dcminter on 09-Jun-2008 22:22

  • Blob field using cmp

    Hi ,
    I need to retrieve the blob data stored in oracle 9i database.
    I am using studio 5 to create a CMP using which the blob field gets mapped to java.io.Serializable class. Oracle thin driver is used and an image of size 1 kb is stored in the table.
    When the client (servlet) calls the method to get the contents of the blob field, the following exceptions are thrown :
    com.sun.jdo.api.persistence.support.JDOFatalDataStoreException: IOException reading serializable object from byte array.
    NestedException: java.io.StreamCorruptedException: invalid stream header
         at com.sun.jdo.spi.persistence.support.ejb.cmp.JDOEJB11HelperImpl.readSerializableObjectFromByteArray(JDOEJB11HelperImpl.java:340)
         at orclblobfolder.orclejb.orclblobBean_1927863344_ConcreteImpl.getImage(orclblobBean_1927863344_ConcreteImpl.java:177)
         at orclblobfolder.orclejb.orclblobBean.getBlobImage(orclblobBean.java:84)
         at orclblobfolder.orclejb.orclblobBean_1927863344_ConcreteImpl_EJBObjectImpl.getBlobImage(orclblobBean_1927863344_ConcreteImpl_EJBObjectImpl.java:22)
         at orclblobfolder.orclejb._orclblobBean_1927863344_ConcreteImpl_EJBObjectImpl_Tie._invoke(Unknown Source)
         at com.sun.corba.ee.internal.POA.GenericPOAServerSC.dispatchToServant(GenericPOAServerSC.java:569)
         at com.sun.corba.ee.internal.POA.GenericPOAServerSC.internalDispatch(GenericPOAServerSC.java:211)
         at com.sun.corba.ee.internal.POA.GenericPOAServerSC.dispatch(GenericPOAServerSC.java:113)
         at com.sun.corba.ee.internal.iiop.ORB.process(ORB.java:275)
         at com.sun.corba.ee.internal.iiop.LocalClientRequestImpl.invoke(LocalClientRequestImpl.java:96)
         at com.sun.corba.ee.internal.corba.ClientDelegate.invoke(ClientDelegate.java:237)
         at com.sun.corba.ee.internal.POA.GenericPOAClientSC.invoke(GenericPOAClientSC.java:97)
         at org.omg.CORBA.portable.ObjectImpl._invoke(ObjectImpl.java:457)
         at orclblobfolder.orclejb._orclblob_Stub.getBlobImage(Unknown Source)
         at orclblobfolder.orclejb._orclblob_Stub.getBlobImage(Unknown Source)
         at test.processRequest(test.java:67)
         at test.doGet(test.java:127)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.StandardWrapperValve.invokeServletService(StandardWrapperValve.java:720)
         at org.apache.catalina.core.StandardWrapperValve.access$000(StandardWrapperValve.java:118)
         at org.apache.catalina.core.StandardWrapperValve$1.run(StandardWrapperValve.java:278)
         at java.security.AccessController.doPrivileged(Native Method)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:274)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:505)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:212)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:505)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:203)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:505)
         at com.iplanet.ias.web.connector.nsapi.NSAPIProcessor.process(NSAPIProcessor.java:157)
         at com.iplanet.ias.web.WebContainer.service(WebContainer.java:598)
    snippet of bean class is :
    public abstract java.io.Serializable getImage();
    public abstract void setImage(java.io.Serializable image);
    public java.io.Serializable getBlobImage() {
    //method which client calls
    return getImage();
    Similar exceptions are thrown when I use poinbase wherein blob data is mapped to byte[] instead of java.io.Serializable.
    Please let me know how can I resolve this problem.
    Thanks a lot,
    -Amol

    How does it effect, when the blob data is stored indatabase using an external source
    The current CMP implementation assumes that a serializable field is stored by serializing it to a byte[] and then storing the byte[] as blob. while retrieving the data, it always tries to de-serialize the byte[] in to a serializable field. Hence if you have stored the data externally, it would fail with "JDOFatalDataStoreException: IOException reading serializable object from byte array."
    Thanks,
    Mitesh

  • Send byte array argeument from pl/sql to java stored procedure?

    I have a java method that accepts an argument of type byte[].
    I want to define a call specification so that it can invoked from a sql statement.
    The Java Developer's Guide show how to map SQL data types to java types and classes, but it is unclear if I can map a SQL data type to an array.
    Does anyone know which SQL type to use to map to a byte array?
    I'm using Oracle 10.2, thus jvm 1.4.2.

    As soon as I posted this question, I saw the RAW to byte[] mapping listed in the documentation. How did I overlook it? Anyway, that what I needed.

  • Should I be able to update a Blob via a ResultSet? (11g driver exception)

    This code fails at the last line:
    stmt = conn.createStatement();
    String tableName = "TBL_esun01_PPP";
    stmt.execute("drop table TBL_esun01_PPP");
    stmt.execute("create table TBL_esun01_PPP (sid int not null primary key, blob_col blob)");
    stmt.close();
    //insert test data
    String blobContent = "WLS JDBC4 test for blob.";
    String blobContentUpdate = "WLS JDBC4 test for UpdateBlob. [Updated]";
    ByteArrayInputStream inputStream = new ByteArrayInputStream(blobContent.getBytes());
    ByteArrayInputStream inputStreamUpdate = new ByteArrayInputStream(blobContentUpdate.getByte
    s());
    String insertSql = "INSERT INTO " + tableName + " VALUES (?, ?)";
    PreparedStatement pstmt = conn.prepareStatement(insertSql);
    int key = 1;
    pstmt.setInt(1, key);
    pstmt.setBlob(2, inputStream);
    pstmt.execute();
    pstmt.close();
    inputStream.close();
    //update data
    String querySql1 = "SELECT sid FROM " + tableName;
    String querySql2 = "SELECT sid, blob_col FROM " + tableName;
    Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_UPDATABLE);
    // we can get updatable resultset in the same way without lob object.
    // following updating can succeed.
    System.out.println("Get updatable resultset using: "+querySql1);
    ResultSet rs = stmt.executeQuery(querySql1);
    rs.next();
    rs.updateInt(1, 2);
    rs.updateRow();
    rs.close();
    inputStreamUpdate.close();
    System.out.println("Get updatable resultset using: "+querySql2);
    try {// failed to get updatable resultset
    rs = stmt.executeQuery(querySql2);
    rs.next();
    rs.updateBlob(2, inputStreamUpdate); // Fails here...
    The driver is 11.1.0.6.0-Production
    The DBMS is Oracle Database 11g Release 11.1.0.0.0 - Production
    Get updatable resultset using: SELECT sid FROM TBL_esun01_PPP
    Get updatable resultset using: SELECT sid, blob_col FROM TBL_esun01_PPP
    We can not get updatable Resultset. Exception message:
    java.sql.SQLException: Invalid operation for read only resultset: updateBlob
    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:112)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:173)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:229)
    at oracle.jdbc.driver.BaseResultSet.updateBlob(BaseResultSet.java:506)
    at TestUpdatableRS.test(TestUpdatableRS.java:84)
    at TestUpdatableRS.main(TestUpdatableRS.java:112)
    thanks,
    Joe

    Joe,
    a) I could not find updateBlob(int, java.io.InputStream). It is updateBlob(int, java.sql.Blob).
    b) I tried the below test and it worked fine, I am using the latest drivers.
    CREATE TABLE BLOB_TABLE (C1 NUMBER, C2 BLOB);
    INSERT INTO BLOB_TABLE VALUES(55, '101011');
    public static void test2(Connection conn) throws SQLException {
    System.out.println("test -");
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
    String query = "select c1, c2 FROM blob_table";
    pstmt = conn.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_UPDATABLE);
    rs = pstmt.executeQuery();
    SQLWarning x = pstmt.getWarnings();
    if (x != null)
    System.out.println(x.getMessage());
    x = rs.getWarnings();
    if (x != null)
    System.out.println(x.getMessage());
    BLOB blob = BLOB.createTemporary(conn, true, BLOB.DURATION_SESSION);
    byte[] b = new byte[50];
    java.util.Arrays.fill(b, (byte) 53);
    blob.putBytes(1L, b);
    if (rs.next()) {
    rs.updateInt(1, 88);
    rs.updateBlob(2, blob);
    rs.updateRow();
    x = rs.getWarnings();
    if (x != null) {
    System.out.println(x.getMessage());
    } catch (SQLException ea) {
    System.out.println(ea);
    } finally {
    if (rs != null) {
    rs.close();
    if (pstmt != null) {
    pstmt.close();
    System.out.println("test - done");
    } // end of test2(Connection);
    ==
    Ashok

  • BLOB insert behavior with thin driver using standard JDBC2.0 and ORACLE-JDBC2.0API

    We have a problem with a BLOB insert to an oracle 8.1.7 DB using Oracle 8.1.7 JDBC thin driver.We get socket read/write error after inserting 32k of data using the standard JDBC2.0 API but using the Oracle JDBC2.0API (using OracleResultSet) it goes fine. We have a requirement to use the standard JDBC2.0 so that our code works with multiple database vendors. Is there another way to get in the blob data with standard JDBC API & using thin driver...?
    thanks,
    Madhu
    Here is my sample test program that does both standard & oracle specific JDBC Blob test insert.
    import java.sql.*;
    import java.io.*;
    import oracle.sql.BLOB;
    import oracle.jdbc.driver.OracleResultSet;
    public class testBLOB {
    //trying to insert a huge file to a BLOB
    static String fileName = "/kernel/genunix";
    public static void main(String[] args) {
    String driverName = "oracle.jdbc.driver.OracleDriver";
    String dbURL = "jdbc:oracle:thin:@localhost:1521:test"; //thin driver
    String user = "BlobTest";
    String passwd = "BlobTest";
    Connection con=null;
    try {
    Class.forName(driverName);
    con=DriverManager.getConnection(dbURL, user,passwd);
    catch (Exception e) {
    e.printStackTrace();
    close(con);
    int i = 0;
    while (i < args.length) {
    if (args.equals("-f"))
    fileName = args[++i];
    i++;
    System.out.println("The file being Stored is: "+fileName);
    createTable(con);
    insertUsingOracleAPI(con);
    insertUsingJDBC20API(con);
    //readDB(con);
    static String getFileName() {
    return fileName;
    public static void close(Connection con) {
    try {
    if (con != null) {
    con.close();
    catch (Exception e) {
    System.exit(-1);
    public static void createTable(Connection con) {
    Statement stmt ;
    try {
    stmt = con.createStatement();
    stmt.execute("DROP TABLE basic_blob_table");
    stmt.close();
    catch (SQLException sqlEx) {
    System.out.println("Dropped the Table");
    try {
    stmt = con.createStatement();
    stmt.execute("CREATE TABLE basic_blob_table ( x varchar2(30), b blob)");
    stmt.close();
    catch (SQLException sqlEx) {
    sqlEx.printStackTrace();
    close(con);
    System.out.println("Created the Table");
    public static void insertUsingOracleAPI(Connection con) {
    OutputStream os = null;
    Statement stmt = null;
    ResultSet rs = null;
    FileInputStream is = null;
    try {
    con.setAutoCommit(false);
    stmt = con.createStatement();
    stmt.execute("INSERT INTO basic_blob_table VALUES( 'OracleAPI', empty_blob())");
    System.out.println("Inserted the dummy Row");
    rs = stmt.executeQuery("Select * from basic_blob_table where x='OracleAPI'");
    if (rs != null && rs.next()) {
    BLOB blob = ((OracleResultSet)rs).getBLOB(2);
    File file = new File(getFileName());
    is = new FileInputStream(file);
    os = blob.getBinaryOutputStream();
    byte[] chunk = new byte[1024];
    int length = -1;
    while((length = is.read(chunk)) != -1)
    os.write(chunk, 0,length);
    System.out.println("Inserted the File " + getFileName() );
    catch (Exception e) {
    e.printStackTrace();
    finally {
    try {
    if (os != null) {
    os.flush();
    os.close();
    if (is != null)
    is.close();
    stmt.close();
    con.commit();
    con.setAutoCommit(true);
    catch (Exception e) {}
    public static void insertUsingJDBC20API(Connection con) {
    PreparedStatement stmt = null;
    FileInputStream is = null;
    try {
    stmt = con.prepareStatement("INSERT INTO basic_blob_table VALUES(?,?)");
    File file = new File(getFileName());
    is = new FileInputStream(file);
    stmt.setString(1,"JDBC20API");
    stmt.setBinaryStream(2,is,(int)file.length());
    stmt.executeUpdate();
    catch (Exception e) {
    e.printStackTrace();
    finally {
    try {
    if (is != null)
    is.close();
    stmt.close();
    catch (Exception e) {}
    null

    Thanks for the response.
    I understand what you are saying...
    that readers don't block writers in Oracle (the same is true in SQL Server 2000).
    However, I don't see how my test case is working correctly with Oracle (the exact same code acting as I'm thinking it should with SQL Server, but I still think it is acting incorrectly with Oracle).
    I have transaction A do this:
    update <table> set <column2>=<value> where <column1>='1'
    then I use Thread.sleep() to make that program hang around for a few minutes.
    Meanwhile I sneak off and start another program which begins transaction B. I have transaction B do this:
    select * from <table> where <column1>='1'
    and the read works immediately (no blocking... just as you have said) however, transaction A is still sleeping, it has not called commit() or rollback() yet.
    So what if transaction A were to call rollback(), the value read by transaction B would be incorrect wouldn't it ?
    Both A and B use setAutoCommit(false) to start their transactions, and then call setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED).
    Isn't that supposed to guarantee that a reader can only read what is committed ?
    And if a row is in "flux"... in the process of having one or more values changed, then the database cannot say what the value will be ?
    I can almost see what you are saying.
    In letting the reader have what it wants without making it wait, I suppose it could be said that Oracle is holding true to the "only let committed data be read"
    So if that's it, then what if I want the blocking ?
    I want an entire row to be locked until whoever it in the middle of updating, adding, or removing it has finished.
    Do you know if that can be done with Oracle ? And how ?
    Thanks again for helping me.

  • Error inserting BLOBs in OC4J 9.0.2.1

    The following snippet of code works in oc4j 9.0.2.0.0 but not in OC4J 9.0.2.1 Any ideas why?
    Thanks,
    Rajiv
    FileInputStream in = new FileInputStream(file.getPath());
    conn.setAutoCommit(false);
    ps = conn.prepareStatement("SELECT blob_info FROM trx_blob WHERE trx_blob_id = ? FOR UPDATE");
    ps.setInt(1, blobID);
    rs = ps.executeQuery();
    rs.next();
    BLOB blob = ((OracleResultSet) rs).getBLOB(1);
    OutputStream outStream = blob.getBinaryOutputStream();
    int size = blob.getBufferSize();
    byte[] buffer = new byte[size];
    int length = -1;
    while ((length = in.read(buffer)) != -1) {
    outStream.write(buffer, 0, length);
    outStream.close();
    in.close();
    conn.commit();
    The error I get is java.sql.SQLException: ORA-01002: fetch out of seqence

    Rajiv -- This looks like bug 2541604. Please ask your support representative for a patch.
    Thanks -- Jeff

  • Using JSP/Servlet to write Word Document to BLOB

    Hi
    I need some help pls
    When I use a normal class with a main method, it loads the word document into a blob and I can read this 100%.Stunning.
    With a JSP/Servlet I cannot get the document out again. The "format" seems to be lost.
    Any ideas,help greatly appreciated:
    Here is the Main class that works:
    package mypackage1;
    import java.io.OutputStream;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.PrintWriter;
    import java.io.IOException;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileReader;
    import java.io.FileNotFoundException;
    import java.io.Writer;
    import java.sql.Connection;
    import oracle.jdbc.*;
    import oracle.jdbc.OracleResultSet;
    import oracle.sql.BLOB;
    import org.apache.log4j.Logger;
    import Util_Connect.DataBase;
    public class TestLOB
    //static final Logger logger = Logger.getLogger("test");
    public TestLOB()
    public static void main(String args[])
    TestLOB testLOB = new TestLOB();
    testLOB.TestLOBInsert("c:\\my_data\\callcenterpilot.doc");
    public void TestLOBInsert(String fileName)
    Connection conn = getConnection("wizard");
    BLOB blob = null;
    try
    conn.setAutoCommit(false);
    String cmd = "SELECT * FROM so_cs.testlob WHERE docno = 1 FOR UPDATE";
    PreparedStatement pstmt = conn.prepareStatement(cmd);
    ResultSet rset = pstmt.executeQuery(cmd);
    rset.next();
    blob = ((OracleResultSet)rset).getBLOB(2);
    File binaryFile = new File(fileName);
    System.out.println("Document length = " + binaryFile.length());
    FileInputStream instream = new FileInputStream(binaryFile);
    OutputStream outstream = blob.getBinaryOutputStream();
    int size = blob.getBufferSize();
    byte[] buffer = new byte[size];
    int length = -1;
    while ((length = instream.read(buffer)) != -1)
    outstream.write(buffer, 0, length);
    instream.close();
    outstream.close();
    conn.commit();
    closeConnection(conn);
    catch (Exception ex)
    System.out.println("Error =- > "+ex.toString());
    private Connection getConnection(String dataBase)
    Connection conn = null;
    try
    DriverManager.registerDriver(new OracleDriver());
    conn = DriverManager.getConnection("jdbc:oracle:thin:@oraclu5:1600:dwz110","so_cs","so_cs");
    catch (Exception ex)
    System.out.println("Error getting conn"+ex.toString());
    return conn;
    private void closeConnection(Connection conn)
    if (conn != null)
    try
    conn.close();
    catch (Exception se)
    System.out.println("Error closing connection in get last imei"+se.toString());
    Works fine:
    Here is the display servlet: Works when main class inserts file
    package mypackage1;
    import java.io.InputStream;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.PrintWriter;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileReader;
    import java.io.FileNotFoundException;
    import java.io.Writer;
    import java.sql.Connection;
    import oracle.jdbc.*;
    import oracle.jdbc.OracleResultSet;
    import oracle.sql.BLOB;
    import org.apache.log4j.Logger;
    import Util_Connect.DataBase;
    public class DisplayLOB extends HttpServlet
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
    static final Logger logger = Logger.getLogger(DisplayLOB.class);
    public void init(ServletConfig config) throws ServletException
    super.init(config);
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    //response.setContentType(CONTENT_TYPE);
    //PrintWriter out = response.getWriter();
    Connection conn = null;
    PreparedStatement pstmt = null;
    try
    conn = getConnection("wizard");
    //out.println("<html>");
    //out.println("<head><title>DisplayLOB</title></head>");
    //out.println("<body>");
    //out.println("<p>The servlet has received a POST. This is the reply.</p>");
    InputStream is=null;
    oracle.sql.BLOB blob=null;
    response.setContentType("application/msword");
    //response.setContentType("audio/mpeg");
    OutputStream os = response.getOutputStream();
    String term = "1";
    String query = "SELECT docdetail FROM testlob WHERE docno = 1";
    pstmt = conn.prepareStatement(query);
    ResultSet rs = pstmt.executeQuery();
    while (rs.next())
    blob=((OracleResultSet)rs).getBLOB(1);
    is=blob.getBinaryStream();
    int pos=0;
    int length=0;
    byte[] b = new byte[blob.getChunkSize()];
    while((length=is.read(b))!= -1)
    pos+=length;
    os.write(b);
    }//try
    catch (Exception se)
    se.printStackTrace();
    finally
    try
    pstmt.close();
    catch (Exception ex)
    System.out.println("Error closing pstmt "+ex.toString());
    //out.println("</body></html>");
    //out.close();
    private Connection getConnection(String dataBase)
    Connection conn = null;
    try
    conn = DataBase.getPoolConnection(dataBase);
    catch (Exception se)
    logger.fatal("Error getting connection: ",se);
    return conn;
    private void closeConnection(Connection conn)
    if (conn != null)
    try
    conn.close();
    catch (Exception se)
    logger.error("Error closing connection in get last imei",se);
    Here is JSP/Servlet
    <%@ page import="org.apache.log4j.*"%>
    <%@ page contentType="text/html; charset=ISO-8859-1" %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>untitled</title>
    <title>Wizard SMS Interface</title>
    <link rel='stylesheet' type='text/css' href='main1.css'>
    <script language='JavaScript' src='copyright.js'></script>
    </head>
    <pre>
    <%
    //HTTP 1.1
    response.setHeader("Cache-Control","no-cache");
    //HTTP 1.0
    response.setHeader("Pragma","no-cache");
    //prevents caching at the proxy server
    response.setDateHeader ("Expires", 0);
    Logger logger = Logger.getLogger("co.za.mtn.wizard.administration.admin01.jsp");
    %>
    </pre>
    <body>
    <FORM ACTION="/WizardAdministration/uploadfile"
    METHOD="POST"
    ENCTYPE="multipart/form-data">
    <INPUT TYPE="FILE" NAME="example">
    <INPUT TYPE="SUBMIT" NAME="button" VALUE="Upload">
    </FORM>
    </body>
    </html>
    <font> <b>Copyright &copy;
    <script>
    var LMDate = new Date( document.lastModified );
    year = LMDate.getYear();
    document.write(display(year));
    </script>
    Mobile Telephone Networks.
    <p align="left"><i><b><font face="Georgia, Times New Roman, Times, serif" size="1"></font></b></i></p>
    package co.za.mtn.wizard.admin;
    import java.io.InputStream;
    import java.util.Enumeration;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.PrintWriter;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileReader;
    import java.io.FileNotFoundException;
    import java.io.Writer;
    import java.sql.Connection;
    import oracle.jdbc.OracleResultSet;
    import oracle.sql.BLOB;
    import org.apache.log4j.Logger;
    import Util_Connect.DataBase;
    public class UploadFile extends HttpServlet
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
    //static final Logger logger = Logger.getLogger(UploadFile.class);
    public void init(ServletConfig config) throws ServletException
    super.init(config);
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    String headerName = null;
    Enumeration en = request.getHeaderNames();
    try
    while ( en.hasMoreElements() )
    Object ob = en.nextElement();
    headerName = ob.toString();
    System.out.println("Value for headerNAme is >"+headerName+"<");
    String aaa = request.getHeader(headerName);
    System.out.println("Value for aa is >"+aaa+"<");
    catch (Exception ex)
    System.out.println("Error in extracting request headers"+ex.toString());
    Connection conn = getConnection("wizard");
    BLOB blob = null;
    try
    conn.setAutoCommit(false);
    String cmd = "SELECT * FROM so_cs.testlob WHERE docno = 1 FOR UPDATE";
    PreparedStatement pstmt = conn.prepareStatement(cmd);
    ResultSet rset = pstmt.executeQuery(cmd);
    rset.next();
    blob = ((OracleResultSet)rset).getBLOB(2);
    //File binaryFile = new File("h:\\callcenterpilot.doc");
    //System.out.println("Document length = " + binaryFile.length());
    //FileInputStream instream = new FileInputStream(binaryFile);
    response.setHeader("Content-Type","application/vnd.ms-word");
    String contentType = request.getContentType();
    System.out.println("Content type received in servlet is >"+contentType+"<");
    ServletInputStream instream = request.getInputStream();
    OutputStream outstream = blob.getBinaryOutputStream();
    int size = blob.getBufferSize();
    byte[] buffer = new byte[size];
    int length = -1;
    while ((length = instream.read(buffer)) != -1)
    outstream.write(buffer, 0, length);
    instream.close();
    outstream.close();
    conn.commit();
    closeConnection(conn);
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    catch (Exception ex)
    System.out.println("Error =- > "+ex.toString());
    //out.println("</body></html>");
    //out.close();
    private Connection getConnection(String dataBase)
    Connection conn = null;
    try
    conn = DataBase.getPoolConnection(dataBase);
    catch (Exception se)
    System.err.println("Error getting connection: "+se.toString());
    return conn;
    private void closeConnection(Connection conn)
    if (conn != null)
    try
    conn.close();
    catch (Exception se)
    System.err.println("Error closing connection in get last imei"+se.toString());
    This is what the display servlet is showing when the JSP/Servlet insert the document
    -----------------------------7d31422224030e
    Content-Disposition: form-data; name="example"; filename="H:\(your name) Skills Matrix.doc"
    Content-Type: application/msword
    �� ࡱ � > ��     � � ���� � � ���������������������
    Tks
    Andre

    hello,
    there are multiple documents out there, describing the oracle reports server setup. try doc.oracle.com for documentation.
    also it is part of the online-documentation.
    you need to install 9iAS enterprise edition. the server is pre-configured and will listen to the url http://yourserver/dev60cgi/rwcgi60.exe
    passing only this url you will get a help-screen, describing the syntax.
    regards,
    the oracle reports team

Maybe you are looking for