BLOBs in JDBC

Is there any way at all that a blob may be created and passed into a packaged stored procedure?
The only working solutions I have seen involve passing the blob into a table directly and then calling an sp with a ref to the table.
We could receive a LONG RAW and put this into a table using a stored procedure called from JDBC but this can't then be converted to a BLOB in the SP because TO_LOB doesn't work inside PL*SQL.
This is a very annoying problem for us, please if anyone has any hints - even if its just a 'oracle doesnt support this' it would be nice just to know!!
Thanks
Jason.

Actually you can pass in a LONG RAW. Also a LONG RAW can be converted to the BLOB you need to put into your Intermedia types, however you can't convert to a BLOB from a LONG RAW in any PL*SQL block at all! This is because TO_LOB only works at the SQL*Plus prompt so you'd just be chasing the wind!
Jason.
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Jake Wheat ([email protected]):
I have also sucessfully passed a blob into an SP but only one that already exists in the database.
There appears to be no way of adding new blobs without using direct table access, unlike ODBC.
I don't know if this is intentional, or if there is a correct method of creating a new blob using only stored procedures.
The only solution I can see is to use LONG RAWs as a means of storage, but I believe intermedia only works with blobs.
Any help would be appreciated,
Jake.<HR></BLOCKQUOTE>
null

Similar Messages

  • How can i put a file into blob using jdbc !?

    Hi
    i tried to put a file into blob , but got a problem.....
    My environment:windows 2000pro,JBuilder 5.0 enterprise,oracle 8.1.6,(not install oracle jdbc driver )
    a part of program(my program is very uglily,if anyone want,later i paste it ba....~_~)
    //Statement stmt2=null;
    //Resultset rs2;
    //opa1 is the blob data
    void saveBlobTableToDisk(Connection con) {
    try {
    stmt2=con.createStatement();
    sqlStr2="SELECT * FROM emp3 where id=1004";
    rs2=stmt2.executeQuery(sqlStr2);
    while (rs2.next()) {
    Blob aBlob=rs2.getBlob("opa1");
    i got the exception :
    " null
    java.lang.UnsupportedOperationException
         at sun.jdbc.odbc.JdbcOdbcResultSet.getBlob(JdbcOdbcResultSet.java:4174)
         at test3.Frame1.saveBlobTableToDisk(Frame1.java:48)
         at test3.Frame1.<init>(Frame1.java:26)
         at test3.Application1.<init>(Application1.java:5)
         at test3.Application1.main(Application1.java:8) "
    and the windows pop up a messagebox said that(about) my memory "0x09af007f" could not read, error in javaw.exe .
    Later i used (ResultSet)getBinaryStream() to solve it. but getBinaryStream() only return a InputStream,so that i can make blob to a file,but i can't make a file to blob using jdbc.....
    I am very stupid that installing sun java, oracle jdbc driver etc....(because i must set a lot of thing such as classpath,java_home etc), Can i only use JBuilder to do that ?
    Or i must install oracle jdbc driver ?
    Thanks.
    D.T.

    My guess here is that Sun's JDBC-ODBC bridge doesn't handle the BLOB datatype. Most ODBC drivers don't support that datatype, so I wouldn't expect the bridge to.
    Is there a reason that you can't use the Oracle driver?
    Justin

  • How to insert an image file as blob using JDBC Statement

    Hi,
    I'm new on java.
    I want the code to insert an image file in Oracle database whose data type is blob.
    i want to use JDBC statement not the prepared statement.
    Please help me out.

    user8739226 wrote:
    thanks for the solution.
    I want to ask one thing
    let say i've created a method in a bean in which i'm passing three parameters.
    One is tablename as String, Second is Name of tablefields as Object, Third is Values as Object
    Like:
    public synchronized int insert(String table,Object[] fields, Object[] values)Ah now we're getting somewhere. I was trying to come up with a situation where using a regular Statement over PreparedStatement would be viable and came up with practically nothing.
    In the method body i'm accessing the table fields and values and combining them into the insert sql query.
    how can i do this using preparedstatment.
    how do i come to know here in this bean that this value is int or string or date at runtime to use setInt, setString, setdate or setBlob respectively.That's your problem. Bad design. You want to make some sort of universal insert method that can insert anything anywhere. But it doesn't really make sense, because whenever you're trying to insert something, you know exactly what you want to insert and where. You could use a PreparedStatement at that point (although encapsulate it in its own method). Now you're trying to create your own poorly designed framework over JDBC that doesn't solve problems, only increases them.
    Above was the only reason i saw, i was using statement instead of preparedstatment as statement was looking easy in this situation.
    please, give me the solution of above using preparedstatment.No, rather you should reconsider your design. What advantage does your insert() method give you over, let's say using a regular PreparedStatement. Granted, you can put your connection opening and other boilerplate code in the method. But if that's your only problem, then your insert method isn't gonna be much use. You could always switch to JPA for example and work with that.

  • Beginner's Question on Inserting a BLOB with JDBC

    What is the easiest way to accept a file from a user and insert it into a BLOB field in a database?
    If it makes a difference - I'm using DB2 and DB2's JDBC driver
    But I would like to know the simpliest solution (maybe even using the JDBC-ODBC bridge)
    -Michael

    Hi Michael,
    with DB2's JDBC driver it is pretty easy:
    You use a prepared statement and the method setBinaryStream or setBytes:
    PreparedStatement pstmt = con.prepareStatement("UPDATE myTable SET blobColumn = ? WHERE ID = ?");
    FileInputStream in = new FileInputStream(...) ;
    pstmt.setBinaryStream(1, in, in.available()) ;
    pstmt.setInt(2, id) ;
    pstmt.execute() ; Or you read the file first into an array of bytes and put it in the database with pstmt.setBytes(...)
    Yannick

  • About update a blob via JDBC

    I want to update a blob value via jdbc.
    The following is my program(part)
    1)String sqlstr = "SELECT * FROM test WHERE vchar='anyone' ";
    2)ResultSet rset = stmt.executeQuery(sqlstr);
    3)BLOB blob = ((OracleResultSet)rset).getBLOB(2);
    4)OutputStream outstream = blob.getBinaryOutputStream();
    when excute the line
    #5)outstream.write(...);
    A IOException throwed. And said "row containing the LOB value is not locked"
    So I change the sqlstr value as
    sqlstr = "SELECT * FROM test WHERE vchar='B' FOR UPDATE";
    Then ,when I restart the programe,it stoped at the line 2) and nothing tell me.
    Just one thing I can do is ctrl-c to corrupt
    it.
    Can you tell me how to resolve it.
    thank you.
    null

    Please take a look at this: http://technet.oracle.com/sample_code/tech/java/sqlj_jdbc/sample_code_index.htm
    You must do
    select ... for update;
    even before you manipulate LOB's.

  • Passing BLOBs through JDBC!

    We cannot pass a BLOB into a PL*SQL Stored Procedure, although we can do this direct into a table and we can happily read a BLOB returned as part of the result of an SP.
    How can we acheive getting a BLOB into the parameter of a PL*SQL stored procedure?
    Any help appreciated,
    Thanks
    Jason.

    If anyone can help, here are some details on the problems I have come across:
    I have Oracle 8.1.7 installed on a i86 running Redhat linux 6.2. I am using the thin driver with JDBC.
    I have the following stored procedures:
    Procedure binarySPA( rsReturn out tDynamicCursor,
    vBinary in BLOB,
    vMimeType in VARCHAR2 );
    Procedure binarySPB( rsReturn out tDynamicCursor,
    vBinary in VARCHAR2,
    vMimeType in VARCHAR2 );
    I am able to add any binaries I like using the second stored procedure plus upload to table like so:
    Connection connection = getConnection();
    connection.setAutoCommit(false);
    Statement st = null;
    ResultSet resultSet = null;
    String guid = null;
    st = connection.createStatement();
    guid = Utils.getUUID();
    st.execute ("INSERT INTO tblBinary VALUES (empty_blob(), '" + guid + "')");
    resultSet = st.executeQuery("SELECT BINARY FROM tblBinary WHERE GUID='" + guid + "' FOR UPDATE");
    resultSet.next();
    BLOB blob = ((OracleResultSet)resultSet).getBLOB(1);
    OutputStream outstream = blob.getBinaryOutputStream();
    int size = blob.getBufferSize();
    byte[] buffer = new byte[size];
    int length = -1;
    while ((length = b.read(buffer)) != -1)
    outstream.write(buffer, 0, length);
    b.close();
    b = null;
    outstream.close();
    and passing the guid to spAddDocBinaryFromTable, which copies the binary from tblBinary and deletes it from tblBinary.
    Unfortunately, this requires external table access, which I would like to avoid, but also doubles the time it takes to add
    a binary to the database. Since some of our clients work with image files upwards of 100mb, adding using this method current takes more
    than ten minutes. I would really like to reduce this time.
    I tried creating the blob using the following java code:
    ====================================
    import java.sql.*;
    import oracle.sql.*;
    import oracle.jdbc.driver.*;
    import java.io.*;
    import java.util.*;
    import java.net.*;
    public class TestBlob4 {
    public static void main(String [] argv) {
    final int USE_BYTE_ARRAY = 0, USE_OUTPUT_STREAM = 2, USE_TEMPORARY_LOB = 3;
    final int TECHNIQUE = USE_TEMPORARY_LOB;
    byte [] testData = "this is some test data".getBytes();
    ByteArrayInputStream testDataStream = new ByteArrayInputStream(testData);
    Connection connection = null;
    CallableStatement st = null;
    ResultSet resultSet = null;
    try {
    oracle.jdbc.pool.OracleConnectionPoolDataSource dataSource = new oracle.jdbc.pool.OracleConnectionPoolDataSource();
    dataSource.setDriverType("thin");
    dataSource.setServerName("xxx");
    dataSource.setDatabaseName("xxx");
    dataSource.setPortNumber(xxx);
    dataSource.setUser("xxx");
    dataSource.setPassword("xxx");
    connection = dataSource.getConnection();
    connection.setAutoCommit(false);
    String stString = "{call XXX.binarySPA(:1,:2,:3)}";
    st = connection.prepareCall(stString);
    st.registerOutParameter(1, oracle.jdbc.driver.OracleTypes.CURSOR);
    BLOB blob;
    switch (TECHNIQUE) {
    case USE_BYTE_ARRAY:
    blob = new BLOB((OracleConnection)connection, testData);
    st.setBlob(2, blob);
    break;
    case USE_OUTPUT_STREAM:
    blob = new BLOB((OracleConnection)connection);
    uploadToBlob(testDataStream, blob);
    st.setBlob(2, blob);
    break;
    case USE_TEMPORARY_LOB:
    blob = BLOB.empty_lob();
    String getString = "{call DBMS_LOB.CreateTemporary(:1,:2)}";
    st = connection.prepareCall(getString);
    st.setBlob(1, blob);
    st.setBoolean(2, false);
    st.execute();
    uploadToBlob(testDataStream, blob);
    st.setBlob(6, blob);
    break;
    st.setObject(3, "text/plain");
    st.execute();
    resultSet = (ResultSet)st.getObject(1);
    resultSet.next();
    System.out.println(resultSet.getString(1));
    connection.commit();
    } catch (Exception e) {
    e.printStackTrace();
    if (connection != null)
    try {
    connection.rollback();
    } catch (SQLException err) {
    err.printStackTrace();
    } finally {
    try {
    if (resultSet != null) resultSet.close();
    if (st != null) st.close();
    if (connection != null) connection.close();
    } catch (SQLException e) {
    e.printStackTrace();
    private static void uploadToBlob(InputStream is, BLOB blob) throws SQLException, IOException {
    OutputStream outstream = blob.getBinaryOutputStream();
    int size = blob.getBufferSize();
    byte[] buffer = new byte[size];
    int length = -1;
    while ((length = is.read(buffer)) != -1)
    outstream.write(buffer, 0, length);
    outstream.close();
    is.close();
    ====================================
    But I get the following errors:
    case USE_OUTPUT_STREAM:
    java.lang.NullPointerException
    at oracle.sql.Datum.getBytes(Datum.java:147)
    at oracle.jdbc.driver.OraclePreparedStatement.setDatum(OraclePreparedStatement.java:1408)
    at oracle.jdbc.driver.OraclePreparedStatement.setBLOB(OraclePreparedStatement.java:1431)
    at oracle.jdbc.driver.OraclePreparedStatement.setObject(OraclePreparedStatement.java:2013)
    at oracle.jdbc.driver.OraclePreparedStatement.setObject(OraclePreparedStatement.java:2052)
    at oracle.sql.LobPlsqlUtil.plsql_getChunkSize(LobPlsqlUtil.java:1201)
    at oracle.sql.LobPlsqlUtil.plsql_getChunkSize(LobPlsqlUtil.java:121)
    at oracle.jdbc.dbaccess.DBAccess.getLobChunkSize(DBAccess.java:955)
    at oracle.sql.LobDBAccessImpl.getChunkSize(LobDBAccessImpl.java:111)
    at oracle.sql.BLOB.getChunkSize(BLOB.java:228)
    at oracle.sql.BLOB.getBufferSize(BLOB.java:242)
    at oracle.sql.BLOB.getBinaryOutputStream(BLOB.java:202)
    at TestBlob4.uploadToBlob(TestBlob4.java:101)
    at TestBlob4.main(TestBlob4.java:55)
    case USE_BYTE_ARRAY:
    java.sql.SQLException: ORA-22281: cannot perform operation with an updated locator
    ORA-06512: at "XXX.XXX", line XXX
    ORA-06512: at line 1
    The PL/SQL code is just an assignment:
    lBinary := vBinary;
    I get the same error when I try an insert the blob into a table.
    case USE_TEMPORARY_LOB:
    PLS-00306: wrong number or types of arguments in call to 'CREATETEMPORARY'
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored
    I can't find any other way to get a blob into the database.
    Any help is much appreciated, as my colleagues and I have been having a nightmare trying to figure this stuff out.
    Jake.
    null

  • How can i put a file into blob(using sun.jdbc.odbc.JdbcOdbcDriver)

    Hi
    i tried to put a file into blob , but got a problem.....
    My environment:windows 2000pro,JBuilder 5.0 enterprise,oracle 8.1.6,(not install oracle jdbc driver )
    a part of program(my program is very uglily,if anyone want,later i paste it ba....~_~)
    //Statement stmt2=null;
    //Resultset rs2;
    //opa1 is the blob data
    void saveBlobTableToDisk(Connection con) {
    try {
    stmt2=con.createStatement();
    sqlStr2="SELECT * FROM emp3 where id=1004";
    rs2=stmt2.executeQuery(sqlStr2);
    while (rs2.next()) {
    Blob aBlob=rs2.getBlob("opa1");
    i got the exception :
    " null
    java.lang.UnsupportedOperationException
         at sun.jdbc.odbc.JdbcOdbcResultSet.getBlob(JdbcOdbcResultSet.java:4174)
         at test3.Frame1.saveBlobTableToDisk(Frame1.java:48)
         at test3.Frame1.<init>(Frame1.java:26)
         at test3.Application1.<init>(Application1.java:5)
         at test3.Application1.main(Application1.java:8) "
    and the windows pop up a messagebox said that(about) my memory "0x09af007f" could not read, error in javaw.exe .
    Later i used (ResultSet)getBinaryStream() to solve it. but getBinaryStream() only return a InputStream,so that i can make blob to a file,but i can't make a file to blob using jdbc.....
    I am very stupid that installing sun java, oracle jdbc driver etc....(because i must set a lot of thing such as classpath,java_home etc), Can i only use JBuilder to do that ?
    Or i must install oracle jdbc driver ?
    Thanks.

    My guess here is that Sun's JDBC-ODBC bridge doesn't handle the BLOB datatype. Most ODBC drivers don't support that datatype, so I wouldn't expect the bridge to.
    Is there a reason that you can't use the Oracle driver?
    Justin

  • BLOB JDBC/OCI8 and dbms_lob.read

    Hi,
    using dbms_lob.read() to retrieve a BLOB with JDBC/OCI8
    we cannot use a chunk larger than 255.
    If we try, we get a 21560 error.
    Any idea?
    Thanks
    Herve
    null

    Thanks for your quick answer.
    I tried it, but doing so, it doubles those characters coming from RAW format to VARCHAR2, and I've got a PNG-file that no picture-viewer shows, not even as garbage as was with CAST_TO_VARCHAR
    file size is now 44246 bytes and debug-output from loop is:
    chunk no:1 chunk size: 8192 chunksize in bytes: 8192
    chunk no:2 chunk size: 8192 chunksize in bytes: 8192
    chunk no:3 chunk size: 8192 chunksize in bytes: 8192
    chunk no:4 chunk size: 8192 chunksize in bytes: 8192
    chunk no:5 chunk size: 8192 chunksize in bytes: 8192
    chunk no:6 chunk size: 3286 chunksize in bytes: 3286
    whole chunk-size: 44246 in bytes: 44246
    Anymore ideas?

  • Sender JDBC Adapter : BLOB

    Hello,
    I am configuring a JDBC Sender adapter and in that SQL query, I want to fetch data from a table which has a column (type BLOB) "Data".
    I want to write a select SQL statement to get the data of BLOB.
    Can you please help me regarding the same.
    Thanks,
    Sandeep Maurya

    Hi
    Check out the below blog, hope it will helps you
    /people/praveen.gujjeti/blog/2010/03/28/sap-xipi-storing-binaries-images-pdfs-etc-in-the-database-blobs-using-jdbc-adapter
    Regards
    Ramg

  • Insertingand retrieving images in database using jdbc

    i am new to jsp.i have to store and retrieve image files using oracle 8i.Then i have to display it using jsp.
    my code for storing image is
    package sample;
    import oracle.jdbc.driver.*;
    import oracle.sql.*;
    import java.sql.*;
    import java.io.*;
    import java.awt.image.*;
    import java.awt.*;
    public class storephoto{
    public static void main(String[] args){
    String filename = "C:/Documents and Settings/user/Desktop/five.gif";
    Connection conn = null;
    try{
    Class.forName("oracle.jdbc.driver.OracleDriver");
    conn=DriverManager.getConnection("jdbc:oracle:thin:@10.1.4.228:1521:data","system","manager");
    conn.setAutoCommit(false);
    Statement st = conn.createStatement();
    int b= st.executeUpdate("insert into bfiles values('"+filename+"', empty_blob())");
    ResultSet rs= st.executeQuery("select * from bfiles for update");
    rs.next();
    BLOB blob=((oracle.jdbc.driver.OracleResultSet)rs).getBLOB(2);
    FileInputStream instream = new FileInputStream(filename);
    System.out.println("instream="+instream);
    OutputStream outstream = blob.getBinaryOutputStream();
    System.out.println("outstream="+outstream);
    int chunk = blob.getChunkSize();
    System.out.println("chunk="+chunk);
    byte[] buff = new byte[chunk];
    int le;
    while( (le=instream.read(buff)) !=-1)
    System.out.println(le);
    outstream.write(buff,0,le);
    System.out.println(buff);
    instream.close();
    outstream.close();
    conn.commit();
    conn.close();
    conn = null;
    System.out.println("Inserted.....");
    catch(Exception e){
    System.out.println("exception"+e.getMessage());
    e.printStackTrace();
    }//catch
    This code works fine & something gets stored in the buffer.but while rereiving nothing gets retreived.i cannot retrieve the image file
    my code for retreiving is
    package sample;
    import java.sql.*;
    import java.io.*;
    import java.awt.*;
    import oracle.sql.BLOB;
    public class retphoto
    public static void main(String a[])
    String fileName ="C:/Documents and Settings/user/Desktop/five.gif";
    try
    Driver driver = new oracle.jdbc.driver.OracleDriver();
    DriverManager.registerDriver(driver);
    Connection con = DriverManager.getConnection("jdbc:oracle:thin:@10.1.4.228:1521:data", "system", "manager");
    File file = new File("C:/Documents and Settings/user/Desktop/sa1.gif");
    FileOutputStream targetFile= new FileOutputStream(file); // define the output stream
    PreparedStatement pstmt = con.prepareStatement("select filecontent from bfiles where filename= ?");
    pstmt.setString(1, fileName);
    ResultSet rs1 = pstmt.executeQuery();
    rs1.next();
    InputStream is = rs1.getBinaryStream(1);
    System.out.println(is);
    byte[] buff = new byte[1024];
    int i = 0;
    while ((i = is.read(buff)) != -1) {
    System.out.println("hai");
    System.out.println(i);
    targetFile.write(buff, 0, i);
    System.out.println("Completed...");
    rs1.close();
    is.close();
    targetFile.close();
    pstmt.close();
    con.close();
    catch(Exception e)
    System.out.println(e);
    }

    Thanks for ur help:
    another Q:
    in my GUI i have a button called Insert. but can't update my database table unless i create textField(e.g Firstname, Surname..ect..), so that when I click Insert button in actionEvent it will bring up popup which have field name in which i am going to insert new records.
    so what iam trying to say is, how iam going to tell the actionEvent to trigger this.
    the following is my code
    public void actionPerformed(ActionEvent event)
    ExamResults exam= new ExamResults ();      
    String studentId = studentTextField.getText();
    if (event.getSource() == insert) //if insert is clicked
    Thanks

  • ClassCastException in oracle.sql.BLOB.createTemporary

    Hi,
    I'm having a ClassCastException problem using the method oracle.sql.BLOB.createTemporary while trying to store a BLOB value (JDBC classes12.jar). The problem is quite clear - if I use the method with a dedicated database connection that specifies the driver as oracle.jdbc.driver.OracleDriver there is no problem - if I use it with an Orion datasource shipped with Oracle IAS10g it gives me a ClassCastException. I imagine that somewhere in the code of this method there is a cast of the underlying connection leading to the ClassCastException when used in conjunction with the Orion datasource. The code to save the BLOB is as follows:
    oracle.sql.BLOB blob = oracle.sql.BLOB.createTemporary(st.getConnection(), false,
    oracle.sql.BLOB.DURATION_SESSION);
    blob.open(BLOB.MODE_READWRITE);
    OutputStream out = blob.getBinaryOutputStream();
    try {
    out.write((byte[])value);
    out.flush();
    out.close();
    } catch (IOException e) {
    throw new SQLException("failed write to blob" + e.getMessage());
    blob.close();
    ((oracle.jdbc.OraclePreparedStatement)(st)).setBLOB(index, blob);
    My questions are:
    (1) is it possibile to save a BLOB type with a different version of Oracle JDBC without having to rely on the Oracle specific implementation of the JDBC interface (the cast of the PreparedStatement to oracle.jdbc.OraclePreparedStatement is quite ugly and not very portable!).
    (2) if not, then how can I get this code to work with the datasource implementation for Oracle IAS.
    thanks in advance for any help.
    Dara.

    If you are using OCI driver, you may check whether using thin driver would avoid ClassCastException.

  • Inserting files in to Oracle 8i database through JDBC - Only 4k data file

    Hi,
    I need to insert a files(images or excel files, doc files etc..) in to oracle 8i database through JDBC program. But i am not able to store more than 4k data files in to files. can any body give me solutions regarding this.
    My code is like this...
    String fileName ="Sample.jpg";
                                  String dataSource = "jdbc/oracle";
                   File file=null;
                   FileInputStream fis = null;
                   Context initCtx=null;
                   DataSource ds = null;
                   Connection con = null;
                   try
                        initCtx = new InitialContext();
                        ds = (DataSource)initCtx.lookup(dataSource);
                        con = ds.getConnection();
                      try
                         file = new File(fileName);
                         fis = new FileInputStream(file);
                        catch(FileNotFoundException fe)
                             out.println("File Not Found");
                                            PreparedStatement pstmt = con.prepareStatement("insert into bfiles values(?,?)");
                        pstmt.setString(1, fileName);
                        pstmt.setBinaryStream(2, fis, (int)file.length());
                        pstmt.executeUpdate();
                        out.println("Inserted");
                        fis.close();
                        pstmt.close();
                        con.close();
                        out.println("closed");
                   catch(Exception e)
                        out.println(e);
               }     in Oracle bi i have created a table like this :
    CREATE TABLE BFILES
      FILENAME     VARCHAR2(100)                    DEFAULT NULL,
      FILECONTENT  BLOB                             DEFAULT EMPTY_BLOB()
    )Please help me ourt to solve this problem.
    i got struck in this problem.
    its urgent
    thanks in advance
    djshivu

    Hi Shanu.
    Thanks for your help...
    By Using THIN driver also we can insert any files more than 4k and and retrive same. Fallowing codes worked fine for me using thin Driver .
    Following are the 2 programs to write and read.
    we can insert and retrieve any format of files ( jpg, gif, doc, xsl, exe, etc...)
    =======================================================
    // Program to insert files in to table
    import oracle.jdbc.driver.*;
    import oracle.sql.*;
    import java.sql.*;
    import java.io.*;
    import java.awt.image.*;
    import java.awt.*;
    * @author  Shivakumar D.J
    * @version
    public class WriteBlob{
    public static void main(String[] args){
    String filename = "018-Annexure-A.xls";
    Connection conn = null;
    try{
        Class.forName("oracle.jdbc.driver.OracleDriver");
        conn=DriverManager.getConnection("jdbc:oracle:thin:@test:1521:orcl","modelytics","modelytics");
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        int b= st.executeUpdate("insert into bfiles values('"+filename+"', empty_blob())");
        ResultSet rs= st.executeQuery("select * from bfiles for update");
        rs.next();
        BLOB blob=((oracle.jdbc.driver.OracleResultSet)rs).getBLOB(2);
        FileInputStream instream = new FileInputStream(filename);
        OutputStream outstream = blob.getBinaryOutputStream();
        int chunk = blob.getChunkSize();
        byte[] buff = new byte[chunk];
        int le;
        while( (le=instream.read(buff)) !=-1)
            outstream.write(buff,0,le);
        instream.close();
        outstream.close();
        conn.commit();
        conn.close();
        conn = null;
        System.out.println("Inserted.....");
       catch(Exception e){
            System.out.println("exception"+e.getMessage());
            e.printStackTrace();
       }//catch
    }=======================
    // Program to retrieve files from database
    [import java.sql.*;
    import java.io.*;
    import java.awt.*;
    public class ReadImage
    public static void main(String a[])
        String fileName ="018-Annexure-A.xls";
        try
              Driver driver = new oracle.jdbc.driver.OracleDriver();
              DriverManager.registerDriver(driver);
              Connection con = DriverManager.getConnection("jdbc:oracle:thin:@test:1521:orcl", "modelytics", "modelytics");
            File file = new File("C:/Documents and Settings/USERID/Desktop/dump.xls");
              FileOutputStream targetFile=  new FileOutputStream(file); // define the output stream
              PreparedStatement pstmt = con.prepareStatement("select filecontent from bfiles where filename= ?");
              pstmt.setString(1, fileName);
               ResultSet rs = pstmt.executeQuery();
               rs.next();
               InputStream is = rs.getBinaryStream(1);
              byte[] buff = new byte[1024];
               int i = 0;
               while ((i = is.read(buff)) != -1) {
                    targetFile.write(buff, 0, i);
                   System.out.println("Completed...");
            is.close();
            targetFile.close();
            pstmt.close();
           con.close();
        catch(Exception e)
              System.out.println(e);
    }====================
    Table Structure is like this
    CREATE TABLE BFILES
      FILENAME     VARCHAR2(100)                    DEFAULT NULL,
      FILECONTENT  BLOB                             DEFAULT EMPTY_BLOB()
    )========================================================
    i hope above codes will helpful for our future programmers
    thanks shanu...
    regards
    djshivu...(javashivu)

  • Display BLOB File (pdf format) from database inside Oracle Form (6i)

    hi all.
    Apologies for a primitive question owing to the fact that i m new to development. I have a requirement to display a pdf document with in an oracle form. i want to know is there any such control for that? or any hint how to go about it?
    thanks in advance

    Here I have found my jsp script...
    How I get the PDF?
    I call my script from pl/sql with
    web.show_document('http://my_server/getblob.jsp?id=' || id_from_my_blob_table || '&baza=myhost:1521:sid','_blank');
    <%@ page contentType="text/html;charset=windows-1250"%>
    <%@ page import="java.sql.*" %>
    <%@ page import="java.util.*" %>
    <%@ page import="java.io.*" %>
    <%@ page import="java.text.*" %>
    <%@ page import="oracle.jdbc.driver.OracleDriver" %>
    <%@ page import="oracle.jdbc.driver.OracleResultSet" %>
    <%
    Connection con = null;
    Statement stmt = null;
    ResultSet rs= null;
    oracle.sql.CLOB clob = null;
    oracle.sql.BLOB blob = null;
    String datoteka = "";
    String host = "http://" + request.getHeader("host") + "/";
    %>
    <!--Peter Valencic 2003 -->
    <html>
    <head>
    <title></title>
    </head>
    <%
       String tip ="";
       String id ="";
       String baza ="";
       String shema ="";
    try
       id = request.getParameter("id");
       baza = request.getParameter("baza");
       shema = request.getParameter("shema");
       if (request.getParameter("id")== null)
          throw new Exception("id= null");
       else if(request.getParameter("id").equals(""))
          throw new Exception("id= null");
       if (request.getParameter("baza")== null)
          throw new Exception("baza= null");
       else if(request.getParameter("baza").equals(""))
          throw new Exception("baza= null");
       if (request.getParameter("shema") == null)
         shema ="";
       else if (request.getParameter("shema").equalsIgnoreCase(""))
         shema="";
       else
         shema =shema + ".";
    catch(Exception e)
       out.println("Priąlo je do napake: " + e.toString());
       return;
          try
                Class.forName("oracle.jdbc.driver.OracleDriver");
                con = DriverManager.getConnection("jdbc:oracle:thin:@"+baza,"your_user","your_password");
                stmt =con.createStatement();
                rs = stmt.executeQuery ("Select * from "+shema+"DOK_VSEBINA_DOKUMENTA_BLOB where ID="+id);
                boolean podatkib = rs.next();
                if (!podatkib)
                   out.print("<li>Ni podatkov za  ID="+id);
                   return;
                blob = ((oracle.jdbc.OracleResultSet)rs).getBLOB("VSEBINA");
                datoteka = rs.getString("NAZIV_DATOTEKE").toUpperCase();
                   File blobFile = new File(application.getRealPath("/uploads/blob")+"/"+datoteka);
                blobFile.createNewFile();
                InputStream podatki = blob.getBinaryStream();
                FileOutputStream strBlob= new FileOutputStream(blobFile);
                int size = blob.getBufferSize();
                byte[] buffer = new byte[size];
                int length = -1;
                while ((length = podatki.read(buffer)) != -1)
                   strBlob.write(buffer,0,length);
                podatki.close();
                strBlob.close();
                con.close();
                out.print("<li>"+host+"in2/uploads/blob/"+datoteka);
                   response.sendRedirect(host+"in2/uploads/blob/"+datoteka);
                //odpremo z jsp-stranjo datoteko..
                //response.sendRedirect("");
          catch(Exception blobException)
             out.print("<li>(BLOB)Napaka pri prebiranju podatkov:</li>"+blobException.toString());
             return;
    out.println("konec..");
    %>
    <body>
    <form method="post">
    Vnesi ID
    <input type=text name="id">
    <li> <input type=submit name="potrdi" >
    </form>
    </body>
    </html>If you look my "old" script..
    first it get 2 parameters baza= database (ip:port:sid), id= id from my table (PK)
    at the end of my script I have:
    response.sendRedirect(host+"in2/uploads/blob/"+datoteka);
    this redirect will redirect you to your file stored on server side..
    Because IE knows what file it must open it will open it with PDF reader...
    hope this help you..
    Edited by: peterv6i.blogspot.com on May 14, 2012 11:14 AM

  • Now, i can put blob into file, but ...............

    Hi
    At first, Thanks Lawrence Guros , from his hint, i did it(put blob into file) using JDBC.
    In addition i find that, using sql*loader "load" a file(150Mb) into database ,need 3 minutes . Using jdbc "take out" the same file ,need 1.5 minutes. Does jdbc is better than sql*loader ?
    So that i tried to load a file using jdbc, i got a problem.......
    My environment:windows 2000pro,JBuilder 5.0 enterprise,oracle 8.1.6,(not install oracle jdbc driver )
    a part of program(my program is very uglily,if anyone want,later i paste it ba....~_~)
    // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    // Statement stmt2=null;
    // Resultset rs2;
    //opa1 is the blob data
    void saveBlobTableToDisk(Connection con) {
    try {
    stmt2=con.createStatement();
    sqlStr2="SELECT * FROM emp3 where id=1004";
    rs2=stmt2.executeQuery(sqlStr2);
    while (rs2.next()) {
    Blob aBlob=rs2.getBlob("opa1");
    i got the exception :
    " null
    java.lang.UnsupportedOperationException
         at sun.jdbc.odbc.JdbcOdbcResultSet.getBlob(JdbcOdbcResultSet.java:4174)
         at test3.Frame1.saveBlobTableToDisk(Frame1.java:48)
         at test3.Frame1.<init>(Frame1.java:26)
         at test3.Application1.<init>(Application1.java:5)
         at test3.Application1.main(Application1.java:8) "
    and the windows pop up a messagebox said that(about) my memory "0x09af007f" could not read, error in javaw.exe .
    Later i used (ResultSet)getBinaryStream() to solve it. but getBinaryStream() only return a InputStream,so that i can make blob to a file,but i can't make a file to blob using jdbc.....
    I am very stupid that installing sun java, oracle jdbc driver etc....(because i must set a lot of thing such as classpath,java_home etc), Can i only use JBuilder to do that ?
    Or i must install oracle jdbc driver ?
    Thanks.
    D.T.

    I would think that SQl*Loader would be faster, but you may want to ask in the SQL*Loader forum for more expert advice.
    I can't tell from your code what you are doing. Is the "opa1" column a image folumn or a straight blob? Which line is 48?
    I only have experience with the oracle JDBC driver. You should be able to use it with jBuilder.
    there is an example of loading an image into an ordimage type at:
    http://otn.oracle.com/training/products/intermedia/media_dev_kit/java_samples_readme.html
    and a more extensive web based photo album:
    http://otn.oracle.com/sample_code/products/intermedia/htdocs/intermedia_servlet_jsp_samples/imedia_servlet_jsp_readme.htm
    And for bulk loading:
    http://otn.oracle.com/sample_code/products/intermedia/htdocs/avi_bulk_loading.html

  • How to read BLOBs as "Java.io.Reader"

    Hello,
    I have a problem dealing with BLOBs in JDBC. I want to get a BLOB as a "java.io.Reader". I have written the following code:
    class Db_templates {
    public static Reader select(int tpl_id) {
    try {
    Connection connection = ... ;
    Reader retour = null;
    String strSQL = "SELECT tpl_blob FROM templates WHERE tpl_id = ?";
    PreparedStatement ps = connection.prepareStatement(strSQL);
    ps.setInt(1, tpl_id);
    ResultSet rset = ps.executeQuery();
    if (rset.next()) {
    oracle.sql.BLOB blob = (BLOB)rset.getObject(1);
    retour = blob.characterStreamValue();
    rset.close();
    ps.close();
    connection.close();
    return retour;
    } catch (SQLException e) {
    return null;
    Then I try to call this method in a JSP file (Tomcat 4.0 as JSP container) with the following lines:
    Reader i = Db_templates.select(42);
    out.println(i.ready());
    char buf[] = new char[1000];
    try {
    int retour = i.read(buf, 1, 900);
    } catch (IOException e) {
    out.println(e.toString());
    The method i.ready() returns false with no IOException thrown.
    The method i.read() fails to execute with the following errors:
    java.lang.NullPointerException
    at oracle.sql.LobPlsqlUtil.plsql_read(LobPlsqlUtil.java:911)
    at oracle.sql.LobPlsqlUtil.plsql_read(LobPlsqlUtil.java:52)
    at oracle.jdbc.dbaccess.DBAccess.lobRead(DBAccess.java:658)
    at oracle.sql.LobDBAccessImpl.getBytes(LobDBAccessImpl.java:95)
    at oracle.sql.BLOB.getBytes(BLOB.java:175)
    at oracle.jdbc.driver.OracleBlobInputStream.needBytes(OracleBlobInputStream.java:126)
    at oracle.jdbc.driver.OracleBufferedStream.read(OracleBufferedStream.java:108)
    at oracle.jdbc.driver.OracleConversionReader.needChars(OracleConversionReader.java:151)
    at oracle.jdbc.driver.OracleConversionReader.read(OracleConversionReader.java:119)
    at org.apache.jsp.essai2$jsp._jspService(essai2$jsp.java:87)
    Any ideas?
    Thanks,
    Nicolas

    Normally, Firefox has two different behaviors for the down arrow key, assuming it is not inside a form control:
    * Scroll the page
    * With caret browsing turned on, move the cursor down one line
    If you are accustomed to the down arrow key moving among search results so you can press the Enter key to load them, and you are using Google, this is due to a script in the results page intercepting those keys and changing what they normally do.
    I have only tested Windows myself, so I don't know whether this is generally available when using Google in your distribution of Linux. If it is, then the question would be: why not on your Firefox? Hmm...

Maybe you are looking for

  • Acrobat pro 9 - save with name lost format of document.

    Hi all !! When save with name a document after modify, it lost the format. A lot of words appear broken with a space between two letters: Example: Before " Your instructions were excellent " After save with name: " Yo ur instru  ctions were excell  e

  • ICal won't display new invites

    Here's my problem. I scheduled events in Outlook on my work computer. I invited myself by sending an e-mail to my mac at home. From Mail, I clicked on the event on my mac. It opened iCal. Then, nothing. It doesn't display, it doesn't allow me to do a

  • ??? in place of arabic caracters

    hi, i'm using oracle 9ids version, in the PCs of my compagnie we change the nls_lang to FRENCH_FRANCE.AR8MSWIN1256 of the forms environnment to be able developping with arabic caracters, and it's ok, but when i unstall oracle 9ids in a server of our

  • Java.rmi.RemoteException: Unexpected fault was returned by the server

    Hi, when we try to have some concurrent request, we've got the following error : java.rmi.RemoteException: Unexpected fault was returned by the server (faultcode: Server.userException, faultstring: java.net.SocketTimeoutException: Read timed out). at

  • I have a very slow startup for a macbook pro after installing Maverick

    I have a very slow startup for a macbook pro after installing Maverick