Writing BLOB column into a csv or txt or sql  files

Hi All,
I am having a requirement where i have to upload a file from user desktop and place that file into a unix directory. For this i am picking that file into a table using APEX and then writing that file in unix directory using UTL_FILE.
The problem which i am facing is that after this every line in my file is having ^M character at the end.
For this i modified my BLOB column into a CLOB column and then also i am facing the same problem.
Is there any way to get rid of this as i have to upload these csv or txt files into tables using sql loader programs. i can;t write any shell script to remove ^M character before uploading as this program will be merge with existing programs and then it will require lots of code change.
Kindly Help.
Thanks
Aryan

Hi Helios,
Thanks again buddy for your reply and providing me different ways.... but still the situation is i can;t write any shell script for removing the ^M. I will be writing into a file from CLOB column.
Actually the scenrio is when i am writing a simple VARCHAR columns with 'W' mode then it is working fine, but i have a BLOB column which stores the data in binary format so i am converting that column into CLOB and then writing it into file with 'W' mode but then i am getting ^M characters. As per your suggestion i have to then again run a program for removing ^M or i have to modify all my previous programs for removing ^M logic.
I want to avoid all these, and just wanted a way so that while writing into a file itself it should not have ^M. Else i have to go for a java stored procedure for running a shell script from sql, and in this still i am having some problem.
Thanks Again Helios for your time and help.
Regards
Aryan

Similar Messages

  • Writing BLOB column into a file (NT/WinWord)

    I need to create
    a file on NT and extract the contents of a BLOB
    column and put it in the file. It's a WORD-document
    and I'm using 8.1.7 on NT4SP5. I'm thinking some
    combination of the LOB package and UTL_FILE, but
    some far no luck. Example code would help me.
    Thanks in advance
    Dannys

    dbms_lob, utl_lob is not supported by oracle, written by an in-
    house analyst to demonstrate a concept.

  • Writing BLOB column from Cobol

    Hi,
    I´m using the Pro*Cobol pre-compile to execute SQL statements into programs Cobol Net Express.
    I need two helps.
    1 - How can do to the Pro*Cobol cut the blanks on the right into PIC X Varying hosts variables ?
    For example :
    ..... LastName VARCHAR(20)
    ..... 05 LASTNAME PIC X(20) VARYING.
    The Pro*Cobol documentation say that precompile transform the elementary item LASTNAME to the group item bellow :
    05 LASTNAME.
    10 LASTNAME-LEN PIC S9(04) COMP.
    10 LASTNAME-ARR PIC X(20).
    When a string less than 20 is moved to LASTNAME-ARR, the exact string lenght is moved to the LASTNAME-LEN and the string is writen
    into DB without blanks on right.
    When a string is red from DB, the precompile write into LASTNAME-LEN the exact string lenght and the LASTNAME-ARR receive the
    string value without blanks on write.
    Occurs that when I compile the program the Pro*Cobol/Micro Focus don´t recognize LASTNAME-LEN and LASTNAME-ARR.
    Am I correct ? May I use any directive that resolve that ?
    2 - I need to check these step-by-step to write a text file generated from cobol into a BLOB column.
    The LOAD FROM FILE statement receive SQLCODE -22275 : Invalid LOB locator specified.
    Assumptions :
    MAG-RELAT-BFILE SQL-BFILE.
    MAG-RELAT-BLOB SQL-BLOB.
    The fiel R1401 exists in D:\Petros\NE\
    Source Code :
    MOVE 'D:\Petros\NE\' TO ALIAS
    MOVE 13 TO ALIAS-L
    MOVE 5 TO FILENAME-L
    MOVE 'R1401' TO FILENAME
    EXEC SQL
    ALLOCATE :IMAG-RELAT-BFILE
    END-EXEC.
    IF SQLCODE NOT EQUAL +0
    MOVE 'ERRO COMANDO ALLOCATE' TO WW-CA-MENSAGEM
    MOVE 'IMAG-RELAT-BFILE' TO WW-CA-ARQUIVO
    MOVE SQLCODE TO WW-ST-ARQUIVO
    MOVE 08 TO RETURNO-CODE
    PERFORM 999-TRATA-ERRO THRU 999-FIM
    END-IF.
    EXEC SQL
    LOB FILE SET :IMAG-RELAT-BFILE
    DIRECTORY = :ALIAS,
    FILENAME = :FILENAME
    END-EXEC.
    IF SQLCODE NOT EQUAL +0
    MOVE 'ERRO COMANDO LOB FILE SET' TO WW-CA-MENSAGEM
    MOVE 'IMAG-RELAT-BFILE' TO WW-CA-ARQUIVO
    MOVE SQLCODE TO WW-ST-ARQUIVO
    MOVE 08 TO RETURNO-CODE
    PERFORM 999-TRATA-ERRO THRU 999-FIM
    END-IF.
    EXEC SQL
    ALLOCATE :IMAG-RELAT-BLOB
    END-EXEC
    IF SQLCODE NOT EQUAL +0
    MOVE 'ERRO COMANDO ALLOCATE' TO WW-CA-MENSAGEM
    MOVE 'IMAG-RELAT-BLOB' TO WW-CA-ARQUIVO
    MOVE SQLCODE TO WW-ST-ARQUIVO
    MOVE 08 TO RETURNO-CODE
    PERFORM 999-TRATA-ERRO THRU 999-FIM
    END-IF.
    EXEC SQL
    LOB LOAD :TOTAL-BYTES
    FROM FILE :IMAG-RELAT-BFILE
    INTO :IMAG-RELAT-BLOB
    END-EXEC.
    IF SQLCODE NOT EQUAL +0
    MOVE 'ERRO COMANDO LOAD FFOM FILE' TO WW-CA-MENSAGEM
    MOVE 'IMAG-RELAT-BFILE, IMAG-RELAT-BLOB' TO WW-CA-ARQUIVO
    MOVE SQLCODE TO WW-ST-ARQUIVO
    MOVE 08 TO RETURNO-CODE
    PERFORM 999-TRATA-ERRO THRU 999-FIM
    END-IF.
    Thanks,

    907466 wrote:
    Hi,
    I´m using the Pro*Cobol pre-compile to execute SQL statements into programs Cobol Net Express.
    I started my career as a cobol programmer in 1981, and the last project I worked on before transitioning to DBA was implementing MF Cobol. It's been a number of years but ...
    I need two helps.
    1 - How can do to the Pro*Cobol cut the blanks on the right into PIC X Varying hosts variables ?
    For example :
    ..... LastName VARCHAR(20)
    ..... 05 LASTNAME PIC X(20) VARYING.
    The Pro*Cobol documentation say that precompile transform the elementary item LASTNAME to the group item bellow :
    05 LASTNAME.
    10 LASTNAME-LEN PIC S9(04) COMP.
    10 LASTNAME-ARR PIC X(20).
    When a string less than 20 is moved to LASTNAME-ARR, the exact string lenght is moved to the LASTNAME-LEN and the string is writen
    into DB without blanks on right.
    When a string is red from DB, the precompile write into LASTNAME-LEN the exact string lenght and the LASTNAME-ARR receive the
    string value without blanks on write.
    Occurs that when I compile the program the Pro*Cobol/Micro Focus don´t recognize LASTNAME-LEN and LASTNAME-ARR.
    Am I correct ? May I use any directive that resolve that ?
    I don't know if you are correct or not. Is the pre-compiler or compiler step throwing an error message? If you are correct, there should be an error message that you should share with us.
    2 - I need to check these step-by-step to write a text file generated from cobol into a BLOB column.
    The LOAD FROM FILE statement receive SQLCODE -22275 : Invalid LOB locator specified.
    Assumptions :
    MAG-RELAT-BFILE SQL-BFILE.
    MAG-RELAT-BLOB SQL-BLOB.
    The fiel R1401 exists in D:\Petros\NE\
    Source Code :
    MOVE 'D:\Petros\NE\' TO ALIAS
    MOVE 13 TO ALIAS-L
    MOVE 5 TO FILENAME-L
    MOVE 'R1401' TO FILENAME
    EXEC SQL
    ALLOCATE :IMAG-RELAT-BFILE
    END-EXEC.
    IF SQLCODE NOT EQUAL +0
    MOVE 'ERRO COMANDO ALLOCATE' TO WW-CA-MENSAGEM
    MOVE 'IMAG-RELAT-BFILE' TO WW-CA-ARQUIVO
    MOVE SQLCODE TO WW-ST-ARQUIVO
    MOVE 08 TO RETURNO-CODE
    PERFORM 999-TRATA-ERRO THRU 999-FIM
    END-IF.
    EXEC SQL
    LOB FILE SET :IMAG-RELAT-BFILE
    DIRECTORY = :ALIAS,
    FILENAME = :FILENAME
    END-EXEC.
    IF SQLCODE NOT EQUAL +0
    MOVE 'ERRO COMANDO LOB FILE SET' TO WW-CA-MENSAGEM
    MOVE 'IMAG-RELAT-BFILE' TO WW-CA-ARQUIVO
    MOVE SQLCODE TO WW-ST-ARQUIVO
    MOVE 08 TO RETURNO-CODE
    PERFORM 999-TRATA-ERRO THRU 999-FIM
    END-IF.
    EXEC SQL
    ALLOCATE :IMAG-RELAT-BLOB
    END-EXEC
    IF SQLCODE NOT EQUAL +0
    MOVE 'ERRO COMANDO ALLOCATE' TO WW-CA-MENSAGEM
    MOVE 'IMAG-RELAT-BLOB' TO WW-CA-ARQUIVO
    MOVE SQLCODE TO WW-ST-ARQUIVO
    MOVE 08 TO RETURNO-CODE
    PERFORM 999-TRATA-ERRO THRU 999-FIM
    END-IF.
    EXEC SQL
    LOB LOAD :TOTAL-BYTES
    FROM FILE :IMAG-RELAT-BFILE
    INTO :IMAG-RELAT-BLOB
    END-EXEC.
    IF SQLCODE NOT EQUAL +0
    MOVE 'ERRO COMANDO LOAD FFOM FILE' TO WW-CA-MENSAGEM
    MOVE 'IMAG-RELAT-BFILE, IMAG-RELAT-BLOB' TO WW-CA-ARQUIVO
    MOVE SQLCODE TO WW-ST-ARQUIVO
    MOVE 08 TO RETURNO-CODE
    PERFORM 999-TRATA-ERRO THRU 999-FIM
    END-IF.
    Thanks,So far you haven't shown us any symptoms, errors, etc. Just a description of what you are doing and a statement that you assume it won't work. Your executable code has a lot of reference to host variables that we can only assume a spelled correctly to match to variables you've declared in your data division. Are you going straight from submitting precompile to run-time, or are you using the very excellent interactive source-level debugger that is a prime feature of MF Cobol?

  • How to get oracle 9i blob column into an itab  in sap using Native SQL

    Hi ,
    We are using SAP ECC 5.0  and we need to coonect to an oracle database ver 9i rel2.
    We need to get the data stored in a blob(pdf/jpeg) into an itab and later
    use it for futher processing.
    I am familiar with using native SQL and I wrote a stored procedure in the non sap oracle database to send the blob info into an internal table in sap.
    But the information is in hex format and the long raw of SAP does not handle this very well.
    Plz see my code below.
    data: itab_insp_drawing like zpicture_cluster(which is of type lraw - 7902 )
          occurs 100 with header line.
    EXEC SQL.
        EXECUTE PROCEDURE
           proc_get_insp_drawings  (
                   IN  :itab-aq_id,
                   IN  :itab-section_id,
                   IN  :t_in_position,
                   out :itab_insp_drawing-picture,
                   OUT :t_blob_length,
                   out :t_out_position,
                   OUT :t_status  )
       ENDEXEC.
      append itab_insp_drawing.
      while t_out_position < t_blob_length.
       EXEC SQL.
        EXECUTE PROCEDURE
           proc_get_insp_drawings  (
                   IN  :itab-aq_id,
                   IN  :itab-section_id,
                   IN  :t_in_position,
                   out :itab_insp_drawing-picture,
                   OUT :t_blob_length,
                   out :t_out_position,
                   OUT :t_status  )
       ENDEXEC.
       append itab_insp_drawing.
       endwhile.
    Any ideas of how to handle blobs from non sap oracle table. I need this blob into an itab in sap.
    Help appreciated.
    Thanks
    Mala

    Please refer the example in this link which deals with Oracle date format.
    You can finnd a command DECODE which is used for date formats. If you have a look at whole theory then you will get an idea.
    Link:[Bulk insert SQL command to transfer data from SAP to Oracle|http://sap.ittoolbox.com/groups/technical-functional/sap-dev/bulk-insert-sql-command-to-transfer-data-from-sap-to-oracle-cl_sql_connection-3780804]

  • Insert Blob column in the client errors ClassCastException: oracle.sql.BLOB

    Hi,
    When I try to insert and commit a Blob column(picture) I am getting the following exception.
    Is there any jar I need to add or any other setup I need to do to accept the BLOB column in the olite client database.
    500 Internal Server Error
    javax.faces.FacesException: #{backing_XXPBWorkOrderResultsCreatePGBean.saveButton_action}: javax.faces.el.EvaluationException: java.lang.ClassCastException: oracle.sql.BLOB
         at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:78)
         at oracle.adf.view.faces.component.UIXCommand.broadcast(UIXCommand.java:211)
    Caused by: java.lang.ClassCastException: oracle.sql.BLOB
         at oracle.lite.poljdbc.LiteEmbPreparedStmt.setVal(Unknown Source)
         at oracle.lite.poljdbc.POLJDBCPreparedStatement.setObject(Unknown Source)
         at oracle.lite.poljdbc.POLJDBCPreparedStatement.setObject(Unknown Source)
         at oracle.lite.poljdbc.POLJDBCPreparedStatement.setObject(Unknown Source)
         at oracle.lite.web.JupPreparedStatement.setObject(Unknown Source)
         at oracle.jbo.server.BaseSQLBuilderImpl.bindUpdateStatement(BaseSQLBuilderImpl.java:1765)
         at oracle.jbo.server.EntityImpl.bindDMLStatement(EntityImpl.java:7345)
    With regareds,
    Kali.
    OSSI.

    Here are examples if inserting into a Blob from text, file, and retrieving a blob.
    Insert into a Blob (Text)
    import java.io.FileNotFoundException;
    import java.sql.Connection;
    import java.sql.Driver;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    public class InsertBlob {
        public static void main(String[] args) throws FileNotFoundException {
            Connection con = null;
            PreparedStatement stmt = null;
            ResultSet rs = null;
            String letterText = "some letter text";
            long id = 100;
            try {
                DriverManager.registerDriver((Driver)(Class.forName("oracle.lite.poljdbc.POLJDBCDriver").newInstance()));
                try {
                    con = DriverManager.getConnection("jdbc:polite:polite", "system", "manager");
                } catch (SQLException sqle) {
                    sqle.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            try {
                stmt = con.prepareStatement("INSERT INTO BLOB_TABLE (BLOB_ID, BLOB_DATA) VALUES (?, EMPTY_BLOB())");
                stmt.setLong(1, id);
                stmt.executeUpdate();
                stmt = con.prepareStatement("SELECT BLOB_DATA FROM BLOB_TABLE WHERE BLOB_ID = ? FOR UPDATE");
                stmt.setLong(1, id);
                rs = stmt.executeQuery();
                if (rs.next()) {
                    try {
                        oracle.lite.poljdbc.BLOB oliteBlob = null;
                        oliteBlob = ((oracle.lite.poljdbc.OracleResultSet) rs).getBLOB(1);
                        byte[] byteLetterText = letterText.getBytes();
                        oliteBlob.putBytes(1, byteLetterText);
                        con.commit();
                    } catch (ClassCastException e) {
                        e.printStackTrace();
                    } finally {
                        rs = null;
                        stmt = null;
                        con.rollback();
                        con = null;
            } catch (SQLException e) {
                e.printStackTrace();
    }Insert Into a Blob (File)
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.sql.Connection;
    import java.sql.Driver;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    public class InsertBlobFile {
        public static void main(String[] args) throws FileNotFoundException {
            Connection con = null;
            PreparedStatement stmt = null;
            long id = 200;
            try {
                DriverManager.registerDriver((Driver)(Class.forName("oracle.lite.poljdbc.POLJDBCDriver").newInstance()));
                try {
                    con = DriverManager.getConnection("jdbc:polite:polite", "system", "manager");
                } catch (SQLException sqle) {
                    sqle.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            try {
                stmt = con.prepareStatement("INSERT INTO BLOB_TABLE (BLOB_ID, BLOB_DATA) VALUES (?, ?)");
                stmt.setLong(1, id);
                File fBlob = new File ( "C:\\BLOB_TEST_FILE.TXT" );
                FileInputStream is = new FileInputStream ( fBlob );
                stmt.setBinaryStream (2, is, (int) fBlob.length() );
                stmt.executeUpdate();
                con.commit();
            } catch (SQLException e) {
                e.printStackTrace();
    }Retrieve from Blob (Write to file)
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.sql.Blob;
    import java.sql.Connection;
    import java.sql.Driver;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    public class RetrieveBlob {
        final static int bBufLen = 32 * 1024;
        final static String outFile = "C:\\BLOB_OUTPUT_FILE.TXT";
        public static void main(String[] args) throws IOException {
            Connection con = null;
            PreparedStatement stmt = null;
            ResultSet rs = null;
            try {
                DriverManager.registerDriver((Driver)(Class.forName("oracle.lite.poljdbc.POLJDBCDriver").newInstance()));
                try {
                    con = DriverManager.getConnection("jdbc:polite:polite", "system", "manager");
                } catch (SQLException sqle) {
                    sqle.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            try {
                stmt = con.prepareStatement("SELECT * FROM BLOB_TABLE");
                rs = stmt.executeQuery();
                while(rs.next()) {
                    int id = rs.getInt(1);
                    Blob value = rs.getBlob(2);
                    System.out.println(id + " | " + value);
                    writeBlobToFile(value);
            } catch (SQLException e) {
                e.printStackTrace();
        public static long readFromBlob(Blob blob, OutputStream out)
          throws SQLException, IOException {
            InputStream in = blob.getBinaryStream();
            int length = -1;
            long read = 0;
            byte[] buf = new byte[bBufLen];
            while ((length = in.read(buf)) > 0) {
                out.write(buf, 0, length);
                read += length;
            in.close();
            return read;
        public static long writeBlobToFile(Blob blob)
          throws IOException, SQLException {
            long wrote = 0;
            OutputStream fwriter = new FileOutputStream(outFile);
            wrote = readFromBlob(blob, fwriter);
            fwriter.close();
            return wrote;
    }

  • How to read a XML file from BLOB column and insert in a table - PL/SQL Only

    Hi,
    To make data load more simple to end user instead placing file on the server and use SQL-LOADER, I came up with new idea that using oracle ebusiness suite attachment functionality. that loads a XML file from local PC to a database column(table is fnd_attachments, default data type is BLOB over here).
    I tried with DBMS_LOB and didnt get around.
    Please can anyone tell me how to read the BLOB column using PL/SQL and store the data in a oracle table. Here's the sample XML file and table structure FYI.
    <?xml version="1.0" encoding="UTF-8"?>
    <dataroot xmlns:od="urn:schemas-microsoft-com:officedata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Corporate_alloc.xsd" generated="2009-07-07T14:17:49">
    <Corporate_alloc>
    <PKG_CODE>BKCORP</PKG_CODE>
    <PKG_NAME>Corporate Edition - Books</PKG_NAME>
    <DET_CODE>B9780080543758</DET_CODE>
    <DET_NAME>Waves, Tides and Shallow-Water Processes</DET_NAME>
    <ALLOCATION_RATIO>0.000041</ALLOCATION_RATIO>
    </Corporate_alloc>
    <Corporate_alloc>
    <PKG_CODE>BKCORP</PKG_CODE>
    <PKG_NAME>Corporate Edition - Books</PKG_NAME>
    <DET_CODE>B9780080534343</DET_CODE>
    <DET_NAME>Hydrostatically Loaded Structures</DET_NAME>
    <ALLOCATION_RATIO>0.000127</ALLOCATION_RATIO>
    </Corporate_alloc>
    </dataroot>
    CREATE TABLE TEST_XML
    ( PKG_CODE VARCHAR2(50),
    PKG_NAME VARCHAR2(100),
    DET_CODE VARCHAR2(20),
    DET_NAME VARCHAR2(500),
    ALLOCATION_RATIO NUMBER )
    Thanks
    EBV

    In regards to #3, use the COLUMNS functionality of XMLTable instead of using Extract. Two simple examples are
    Re: XML Data - Caliculate fields
    Re: Extractvalue function not recognised

  • Problems writing BLOB data into O8i (ADO and AppendChunk)

    We have a table where you want to store bianry data (BLOBs). I
    have used the LONG RAW datatype to store this information. Here
    is the code for the table:
    CREATE TABLE "CONTENTBLOBTABLE" (
    DIGEST NVARCHAR2(40) NOT NULL,
    BLOB LONG RAW,
    CHECK (DIGEST IS NOT NULL),
    PRIMARY KEY (DIGEST)
    Then we try to update this table with ADO 2.6 on a Windows 200
    machine with Oracle ODBC driver. Here is the relevant code
    snippet:
    // set the value of the field
    pRs->AddNew();
    pRs->Fields->GetItem("DIGEST")->PutValue(strDigest);
    pRs->Fields->GetItem("BLOB")->AppendChunk(varBLOB);
    if(!pRs->Update())
    C_LOG_CRITICAL(L"CC_CS_DAL::WriteBLOB - pRs->Update failed");
    *error = C_CS_CBT_ERROR;
    pRs->CancelUpdate();
    pRs->Close();
    m_pConn->Close();
    m_spObjectContext->SetAbort();
    return S_FALSE;
    OK, NO error occurs: no exception, HRESULT return values are all
    OK, method completes.
    BUT: there is no data in the table!?!?! When querying the exact
    same table we get an empty result!
    Any ideas please?
    Thanks,
    Christian

    Did you even get a reply to this message?

  • How to read the blob column?

    Hi,
    i wanted to store the zip file in a blob column and i also want to download the file
    i have tried in the following manner
    -- Creation of the table
    create table demo
    ( ID int,
    theblob blob);
    --insert the zip file into the table
    declare
    l_blob blob;
    l_bfile bfile;
    begin
    insert into demo values ( 5, empty_blob() )
    returning theBlob into l_blob;
    l_bfile := bfilename( 'MWDIR_TST', 'demo.zip' );
    dbms_lob.fileopen( l_bfile );
    dbms_lob.loadfromfile( l_blob, l_bfile,
    dbms_lob.getlength( l_bfile ) );
    dbms_lob.fileclose( l_bfile );
    end;
    -- Function to convert the blob into clob
    CREATE OR REPLACE FUNCTION XBLOB_To_CLOB(L_BLOB BLOB) RETURN CLOB IS
    L_CLOB               CLOB;
    L_SRC_OFFSET     NUMBER;
    L_DEST_OFFSET     NUMBER;
    L_BLOB_CSID          NUMBER := DBMS_LOB.DEFAULT_CSID;
    V_LANG_CONTEXT     NUMBER := DBMS_LOB.DEFAULT_LANG_CTX;
    L_WARNING          NUMBER;
    L_AMOUNT          NUMBER;
    BEGIN
    IF DBMS_LOB.GETLENGTH(L_BLOB) > 0 THEN
    DBMS_LOB.CREATETEMPORARY(L_CLOB, TRUE);
    L_SRC_OFFSET := 1;
    L_DEST_OFFSET := 1;
    L_AMOUNT := DBMS_LOB.GETLENGTH(L_BLOB);
    DBMS_LOB.CONVERTTOCLOB(L_CLOB,
    L_BLOB,
    L_AMOUNT,
    L_SRC_OFFSET,
    L_DEST_OFFSET,
    1,
    V_LANG_CONTEXT,
    L_WARNING);
    RETURN L_CLOB;
    ELSE
    L_CLOB:= TO_CLOB('');
    RETURN L_CLOB;
    End IF;
    DBMS_LOB.FREETEMPORARY(L_CLOB);
    END XBLOB_To_CLOB;
    -- Procedure to wtire clob into file
    CREATE OR REPLACE PROCEDURE Write_CLOB_To_File ( directory_name varchar2,filename varchar2, clob_loc CLOB )
    IS
    buffer VARCHAR2(32767);
    buffer_size CONSTANT BINARY_INTEGER := 32767;
    amount BINARY_INTEGER;
    offset NUMBER(38);
    file_handle UTL_FILE.FILE_TYPE;
    BEGIN
    file_handle := UTL_FILE.FOPEN(location => directory_name,filename => filename,open_mode => 'w',max_linesize => buffer_size);
    amount := buffer_size;
    offset := 1;
    -- READ FROM CLOB / WRITE OUT TO DISK
    WHILE amount >= buffer_size
    LOOP
    DBMS_LOB.READ(lob_loc => clob_loc,amount => amount,offset => offset,buffer => buffer);
    buffer:=replace(buffer,chr(13),'');
    offset := offset + amount;
    UTL_FILE.PUT(file => file_handle,buffer => buffer);
    UTL_FILE.FFLUSH(file => file_handle);
    END LOOP;
    UTL_FILE.FCLOSE(file => file_handle);
    END Write_CLOB_To_File;
    -- To execute use the following example
    declare TmpClob CLOB;
    begin
    select XBLOB_TO_CLOB(theblob) into TmpClob from demo where id=5;
    Write_Clob_To_File('TEMP','demo.txt',TmpClob);
    end;
    when i am excuting the above code it is not bringing the exact binary values from the database ?
    can any one help me on this?
    Thanks
    Rangan S

    On another note it's always a good idea to tell us what database version you are using e.g. 9.2.0.7 or 10.2.0.3 etc. as this will allow us to tailor our answers appropriately in case there are features we can't use because you are using an older version.
    And, when posting code, please put {noformat}{noformat} tags around it so that it keeps its formatting on the forum.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to convert blob data into clob using plsql

    hi all,
    I have requirement to convert blob column into clob .
    version details
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - Production
    PL/SQL Release 11.1.0.7.0 - Production
    CORE     11.1.0.7.0     Production
    TNS for 32-bit Windows: Version 11.1.0.7.0 - Production
    NLSRTL Version 11.1.0.7.0 - Production
    DECLARE
       v_blob      temp.blob_column%TYPE;------this is blob data type column contains  (CSV file which is  inserted  from screens)
       v_clob      CLOB; --i want to copy blob column data into this clob
       v_warning   NUMBER;
    BEGIN
       SELECT blob_column
         INTO v_blob
         FROM temp
        WHERE pk = 75000676;
       DBMS_LOB.converttoclob (dest_lob          => v_clob,
                               src_blob          => v_blob,
                               amount            => DBMS_LOB.lobmaxsize,
                               dest_offset       => 1,
                               src_offset        => 1,
                               blob_csid         => 1, -- what  is the use of this parameter
                               lang_context      => 1,
                               warning           => v_warning
       DBMS_OUTPUT.put_line (v_warning);
    EXCEPTION
       WHEN OTHERS
       THEN
          DBMS_OUTPUT.put_line (SQLCODE);
          DBMS_OUTPUT.put_line (SQLERRM);
    END;I am not getting what is the use of blob_csid , lang_context parameters after going the trough the documentation .
    Any help in this regard would be highly appreciated .......
    Thanks
    Edited by: prakash on Feb 5, 2012 11:41 PM

    Post the 4 digit Oracle version.
    Did you read the Doc for DBMS_LOB.CONVERTTOCLOB? - http://docs.oracle.com/cd/B28359_01/appdev.111/b28419/d_lob.htm
    The function can convert data from one character set to another. If the source data uses a different character set than the target you need to provide the character set id of the source data.
    The blob_csid parameter is where you would provide the value for the source character set.
    If the source and target use the same character set then just pass zero. Your code is passing a one.
    >
    General Notes
    You must specify the character set of the source data in the blob_csid parameter. You can pass a zero value for blob_csid. When you do so, the database assumes that the BLOB contains character data in the same character set as the destination CLOB.
    >
    Same for 'lang_context' - your code is using 1; just use 0. It is an IN OUT
    >
    lang_context
    (IN) Language context, such as shift status, for the current conversion.
    (OUT) The language context at the time when the current conversion is done.
    This information is returned so you can use it for subsequent conversions without losing or misinterpreting any source data. For the very first conversion, or if do not care, use the default value of zero.

  • Error reading data from CLOB column into VARCHAR2 variable

    Hi all,
    Am hitting an issue retrieving data > 8K (minus 1) stored in a CLOB column into a VARCHAR2 variable in PL/SQL...
    The "problem to be solved" here is storing DDL, in this case a "CREATE VIEW" statement, that is longer than 8K for later retrieval (and execution) using dynamic SQL. Given that the EXECUTE IMMEDIATE statement can take a VARCHAR2 variable (up to 32K(-1)), this should suffice for our needs, however, it seems that somewhere in the process of converting this VARCHAR2 text to a CLOB for storage, and then retrieving the CLOB and attempting to put it back into a VARCHAR2 variable, it is throwing a standard ORA-06502 exception ("PL/SQL: numeric or value error"). Consider the following code:
    set serveroutput on
    drop table test1;
    create table test1(col1 CLOB);
    declare
    cursor c1 is select col1 from test1;
    myvar VARCHAR2(32000);
    begin
    myvar := '';
    for i in 1..8192 loop
    myvar := myvar || 'a';
    end loop;
    INSERT INTO test1 (col1) VALUES (myvar);
    for arec in c1 loop
    begin
    myvar := arec.col1;
    dbms_output.put_line('Read data of length ' || length(myvar));
    exception when others then
    dbms_output.put_line('Error reading data: ' || sqlerrm);
    end;
    end loop;
    end;
    If you change the loop upper bound to 8191, all works fine. I'm guessing this might have something to do with the database character set -- we've recently converted our databases over to UTF-8, for Internationalizion support, and that seems to have changed underlying assumptions regarding character processing...?
    As far as the dynamic SQL issue goes, we can probably use the DBMS_SQL interface instead, with it's EXECUTE procedure that takes a PL/SQL array of varchar2(32K) - the only issue there is reading the data from the CLOB column, and then breaking that data into an array but that doesn't seem insurmountable. But this same basic issue (when a 9K text block, let's say, turns into a >32K block after being CLOBberred) seems to comes up in other text-processing situations also, so any ideas for how to resolve would be much appreciated.
    Thanks for any tips/hints/ideas...
    Jim

    For those curious about this, here's the word from Oracle support (courtesy of Metalinks):
    RESEARCH
    ========
    Test the issue for different DB version and different characterset.
    --Testing the following PL/SQL blocks by using direct assignment method(myvar := arec.col1;) on
    different database version and different characterset.
    SQL>create table test1(col1 CLOB);
    --Inserting four CLOB data into test1.
    declare
    myvar VARCHAR2(32767);
    begin
    myvar := RPAD('a',4000);
    INSERT INTO test1 (col1) VALUES (myvar);
    myvar := RPAD('a',8191);
    INSERT INTO test1 (col1) VALUES (myvar);
    myvar := RPAD('b',8192);
    INSERT INTO test1 (col1) VALUES (myvar);
    myvar := RPAD('c',32767);
    INSERT INTO test1 (col1) VALUES (myvar);
    commit;
    end;
    --Testing the direct assignment method.
    declare
    cursor c1 is select col1, length(col1) len1 from test1;
    myvar VARCHAR2(32767);
    begin
    for arec in c1 loop
    myvar := arec.col1;
    --DBMS_LOB.READ(arec.col1, arec.len1, 1, myvar);
    dbms_output.put_line('Read data of length: ' || length(myvar));
    end loop;
    end;
    The following are the summary of the test results:
    ===================================
    1. If the database characterset is WE8ISO8859P1, then the above direct assignment
    method(myvar := arec.col1;) works for database version 9i/10g/11g without any
    errors.
    2. If the database characterset is UTF8 or AL32UTF8, then the above direct assignment method(myvar := arec.col1;) will generate the "ORA-06502:
    PL/SQL: numeric or value error" when the length of the CLOB data is greater
    than 8191(=8K-1). The same error can be reproduced across all database versions
    9i/10g/11g.
    3. Using DBMS_LOB.READ(arec.col1, arec.len1, 1, myvar) method to read CLOB data into a VARCHAR2 variable works for both WE8ISO8859P1 and UTF8
    characterset and for all database versions.
    So - it seems as I'd surmised, UTF8 changes the way VARCHAR2 and CLOB data is handled. Not too surprising, I suppose - may you all be lucky enough to be able to stay away from this sort of issue. But - the DBMS_LOB.READ workaround is certainly sufficient for the text processing situations we find ourselves in currently.
    Cheers,
    Jim C.

  • How to open a BLOB column stored in oracle using OLE wrappers

    Hello friends
    I have a strange problem, I have OLE objects like, *.doc, *.xls, *.bmp etc all these files have been embedded in oracle database using OLE2.0 & wrapping technology. Well I have to extract this data outof BLOB column from Oracle database & store it in OS file in its respective format
    For Eg. If the BloB data which has been embedded in Oracle database using OLE2.0 & wrapping is of *.doc file then the OS file which I have stored after extraction I should be able to open in MS word.
    Well in this task I am able to extract the file using GETCHUNK feature from VB , but I am not able to open the OS file in MS word as it is saying the error
    the document you are trying to open is not supported by MS Word
    So please any one of you can help me to solve this problem I wil be very helpful. also if you have suported code for ths problem It is welcome
    Not only using VB if you have code of any other langauges also itis welcomed
    Thanks
    Adhem

    Please "Preview" your future posts. Your formatting is awful. Especially learn to use the [ code ] tags.
    Are you sure DateTime.Now.ToString() returns a string in the format of 'MM/DD/YYYY HH:MI:SS.FF3'?
    Fix that and if you still having the problems, debug the actual result of your string.Format() and post that.

  • Uploading a file (.doc, .xls, .txt) into an Oracle table with BLOB column

    Hello All :
    I have been trying to figure out for a simple code I can use in my JSP to upload a file (of any format) into an Oracle table with a BLOB column type. I have gone through a lot of existing forums but couldnot find a simple code (that doesnot use Servlet, for eg.) to implement this piece.
    Thanks a lot for your help !!

    Hi.
    First of all to put a file into Oracle you need to get the array of bytes byte[] for that file. For this use for example FileInputStream.
    After you get the byte array try to use this code:
            try {
                Connection conn = myGetDBConnection();
                PreparedStatement pstmt = conn.prepareStatement("INSERT INTO table1 (content) VALUES(?)");
                byte[] content = myGetFileAsBytes();
                if (content != null) {
                    pstmt.setBinaryStream(0, new ByteArrayInputStream(content), content.length);
                pstmt.close();
                conn.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }or instead of using ByteArrayInputStream try pstmt.setBinaryStream(0, new FileInputStream(yourFile), getFileSize());Hope this will help...
    regards, Victor Letunovsky

  • Getting errors while writing to a BLOB column using PrepareStatement

    Hello,
    I am getting the following errors when I am trying to insert in a BLOB in the oracle 9i database:
    java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1 ORA-06502: PL/SQL: numeric or value error ORA-06512: at line 205 ORA-22297: warning: Open LOBs exist at transaction commit time
    It gets inserted into the BLOB column correctly even after throwing exception.I am using the following code:
    String outputXML = outputXML //Some huge string having a length of 52k
    String pKey = "DATA-WORKATTACH-URL MELLONFINCORP-GSS-CPG E-444!20061130T211932.030 GMT";
    String createDateTime = "20061212T145931.448 GMT";
    String createOpName = "Haque, Nadeem";
    String createOperator = "ADCDTB6";
    String createSystemID = "WFE";
    String insName = "TESt INS";
    String objClass = "Data-WorkAttach-Note";
    String updateDateTime = "20061207T191900.510 GMT";
    String updateOpName = "Haque, Nadeem";
    String updateOperator = "ADCDTB6";
    String updateSystemID = "WFE";
    String label = "This is a test for label";
    String attachDate = "20061207T191900.510 GMT";
    String attachedBy = "Nadeem";
    String attachName = "Nadeem Haque";
    String note = "This is a test note";
    String refObjectKey = "E-438!20061130T211932.030";
    String replicationDate = "20061207T191900.510 GMT";
    try{
    java.sql.PreparedStatement pstmt = null;
    java.sql.Statement stmt = null;
    java.io.OutputStream tempBlobOStream = null;
    oracle.sql.BLOB tempBlob = null;
    javax.naming.Context ctx = new javax.naming.InitialContext();
    tools.findPage("tempWorkPage").putString ("testctx", ctx.toString());     
    javax.sql.DataSource ds = (javax.sql.DataSource)ctx.lookup("jdbc/gswWorkflowReportingData");
    tools.findPage("tempWorkPage").putString ("testds", ds.toString());
    java.sql.Connection conn = ds.getConnection();
    tools.findPage("tempWorkPage").putString ("testconn", conn.toString());
    java.sql.ResultSet lobDetails = null;
         try{
              byte [] ba = outputXML.getBytes();
              String query = "INSERT INTO GSW06U.pc_data_workattach(PZINSKEY,PXCREATEDATETIME,ATTACHDATE,PXUPDATEDATETIME,PXCREATEOPNAME,PXCREATEOPERATOR,PXCREATESYSTEMID,PXINSNAME,PXOBJCLASS,PXUPDATEOPNAME,PXUPDATEOPERATOR,PXUPDATESYSTEMID,PYLABEL,ATTACHEDBY,ATTACHNAME,NOTE,REFOBJECTKEY,ATTACHSTREAM) values(?,to_date(concat(substr(?,1,8),substr(?,10,6)),'YYYYMMDDHH24MISS'),to_date(concat(substr(?,1,8),substr(?,10,6)),'YYYYMMDDHH24MISS'),to_date(concat(substr(?,1,8),substr(?,10,6)),'YYYYMMDDHH24MISS'),?,?,?,?,?,?,?,?,?,?,?,?,?,EMPTY_BLOB())";
              tools.findPage("tempWorkPage").putString ("query", query);
              pstmt = conn.prepareStatement(query);
              pstmt.setString(1, pKey); // Bind PZINSKEY
              pstmt.setString(2, createDateTime); // Bind PZINSKEY
              pstmt.setString(3, createDateTime);
              pstmt.setString(4, attachDate);
              pstmt.setString(5, attachDate);
              pstmt.setString(6, updateDateTime);
              pstmt.setString(7, updateDateTime);
              pstmt.setString(8, createOpName);
              pstmt.setString(9, createOperator);
              pstmt.setString(10, createSystemID);
              pstmt.setString(11, insName);
              pstmt.setString(12, objClass);
              pstmt.setString(13, updateOpName);
              pstmt.setString(14, updateOperator);
              pstmt.setString(15, updateSystemID);
              pstmt.setString(16, label);
              pstmt.setString(17, attachedBy);
              pstmt.setString(18, attachName);
              pstmt.setString(19, note);
              pstmt.setString(20, refObjectKey);
              pstmt.execute(); // Execute SQL statement
              // Retrieve the row just inserted, and lock it for insertion of the LOB columns
              stmt = conn.createStatement();
              lobDetails = stmt.executeQuery("SELECT AttachStream FROM GSW06U.pc_data_workattach WHERE PZINSKEY = '" + pKey + "' FOR UPDATE");
              tools.findPage("tempWorkPage").putString ("idvalue", pKey);
              // Retrieve Blob streams for AttachStream column and load the sample XML
              if( lobDetails.next()) {
              //Get the CLOB from the resultset
              tempBlob = (oracle.sql.BLOB)lobDetails.getBlob(1);
              tools.findPage("tempWorkPage").putString ("pos1", "at pos1");
              // Open the temporary CLOB in readwrite mode, to enable writing
              tempBlob.open(oracle.sql.BLOB.MODE_READWRITE);
              tools.findPage("tempWorkPage").putString ("pos2", "at pos2");
              // Get the output stream to write
              tempBlobOStream = tempBlob.getBinaryOutputStream();
              tools.findPage("tempWorkPage").putString ("pos3", "at pos3");
              // Write the data into the temporary CLOB from the byte array
              tempBlobOStream.write(ba);
              // Flush and close the stream
              tempBlobOStream.flush();
              conn.commit();
              //Close everything
    tempBlobOStream.close();
              tempBlobOStream = null;
              tempBlob.close();
              tempBlob =null;
              lobDetails.close();
              lobDetails = null;
              stmt.close();
              stmt = null;
              pstmt.close();
              pstmt = null;
              conn.close(); // Return to connection pool
              conn = null; // Make sure we don't close it twice
         catch(java.sql.SQLException sqlexp) {
                   tempBlob.freeTemporary();
                   sqlexp.printStackTrace();
                   tools.findPage("tempWorkPage").putString ("SQLException", sqlexp.toString());
         catch(java.lang.Exception exp) {
                   tempBlob.freeTemporary();
                   tools.findPage("tempWorkPage").putString ("InnerException", exp.toString());
                   exp.printStackTrace();
         finally
              if (lobDetails != null) {
              try { lobDetails.close(); } catch (java.sql.SQLException e) { System.out.println(" Error while Freeing Result sets" + e.toString()); }
              lobDetails = null;
              if (stmt != null) {
              try { stmt.close(); } catch (java.sql.SQLException e) {System.out.println(" Error while Freeing java Statement" + e.toString()); }
              stmt = null;
              if (pstmt != null) {
              try { pstmt.close(); } catch (java.sql.SQLException e) {System.out.println(" Error while Freeing java PrepareStatement" + e.toString()); }
              pstmt = null;
              try{
              if (tempBlob != null) {
         // If the BLOB is open, close it
         if (tempBlob.isOpen()) {
         tempBlob.close();
         // Free the memory used by this BLOB
         tempBlob.freeTemporary();
              tempBlob = null;
              catch (Exception ex) { // Trap errors
              System.out.println(" Error while Freeing LOBs : " + ex.toString());
              if (conn != null) {
              try { conn.close(); } catch (java.sql.SQLException e) { System.out.println(" Error while Freeing Connection" + e.toString()); }
              conn = null;
    catch(java.lang.Exception e)
         tools.findPage("tempWorkPage").putString ("LangException", e.toString());
         e.printStackTrace();
    }

    Hello,
    I am getting the following errors when I am trying to
    insert in a BLOB in the oracle 9i database:
    java.sql.SQLException: ORA-00604: error occurred
    at recursive SQL level 1 ORA-06502: PL/SQL: numeric
    or value error ORA-06512: at line 205 ORA-22297:
    warning: Open LOBs exist at transaction commit
    time
    You're doing exactly what the error says, that is committing with an open LOB. Look at the following piece of code: you write in the LOB, you flush it and then commit. There is no closing of the LOB stream before committing.
    Try putting the tempBlobOStream.close() instruction before the commit.
    // Write the data into the temporary CLOB from the
    he byte array
              tempBlobOStream.write(ba);
              // Flush and close the stream
              tempBlobOStream.flush();
    nn.commit();
              //Close everything
    tempBlobOStream.close();

  • How to insert a pdf or jpeg image into a blob column of a table

    How to insert a pdf or jpeg image into a blob column of a table

    Hi,
    Try This
    Loading an image into a BLOB column and displaying it via OAS
    The steps are as follows:
    Step 1.
    Create a table to store the blobs:
    create table blobs
    ( id varchar2(255),
    blob_col blob
    Step 2.
    Create a logical directory in the database to the physical file system:
    create or replace directory MY_FILES as 'c:\images';
    Step 3.
    Create a procedure to load the blobs from the file system using the logical
    directory. The gif "aria.gif" must exist in c:\images.
    create or replace procedure insert_img as
    f_lob bfile;
    b_lob blob;
    begin
    insert into blobs values ( 'MyGif', empty_blob() )
    return blob_col into b_lob;
    f_lob := bfilename( 'MY_FILES', 'aria.gif' );
    dbms_lob.fileopen(f_lob, dbms_lob.file_readonly);
    dbms_lob.loadfromfile( b_lob, f_lob, dbms_lob.getlength(f_lob) );
    dbms_lob.fileclose(f_lob);
    commit;
    end;
    Step 4.
    Create a procedure that is called via Oracle Application Server to display the
    image.
    create or replace procedure get_img as
    vblob blob;
    buffer raw(32000);
    buffer_size integer := 32000;
    offset integer := 1;
    length number;
    begin
    owa_util.mime_header('image/gif');
    select blob_col into vblob from blobs where id = 'MyGif';
    length := dbms_lob.getlength(vblob);
    while offset < length loop
    dbms_lob.read(vblob, buffer_size, offset, buffer);
    htp.prn(utl_raw.cast_to_varchar2(buffer));
    offset := offset + buffer_size;
    end loop;
    exception
    when others then
    htp.p(sqlerrm);
    end;
    Step 5.
    Use the PL/SQL cartridge to call the get_img procedure
    OR
    Create that procedure as a function and invoke it within your PL/SQL code to
    place the images appropriately on your HTML page via the PL/SQL toolkit.
    from a html form
    1. Create an HTML form where the image field will be <input type="file">. You also
    need the file MIME type .
    2. Create a procedure receiving the form parameters. The file field will be a Varchar2
    parameter, because you receive the image path not the image itself.
    3. Insert the image file into table using "Create directory NAME as IMAGE_PATH" and
    then use "Insert into TABLE (consecutive, BLOB_OBJECT, MIME_OBJECT) values (sequence.nextval,
    EMPTY_BLOB(), 'GIF' or 'JPEG') returning BLOB_OBJECT, consecutive into variable_blob,
    variable_consecutive.
    4. Load the file into table using:
    dbms_lob.loadfromfile(variable_blob, variable_file_name, dbms_lob.getlength(variable_file_name));
    dbms_lob.fileclose(variable_file_name);
    commit.
    Regards,
    Simma........

  • Sample insert into table with BLOB column

    This is my first opportunity to work with BLOB columns. I was wondering if anyone had some sample code that shows the loading of a blob column and inserted into the table with a blob column.
    I have to produce a report (including crlf) and place it into a blob column. The user will download the report at a later time.
    Any suggestions / code samples are greatly appreciated!!!!

    You can enable string binding in TopLink.
    login.useStringBinding(int size);
    or you could enable binding in general,
    login.bindAllParameters();

Maybe you are looking for

  • Help reading a .txt file from the hard drive....

    Hi guys, Ok... I need to know how to read a .txt file from the hard drive... I have an example on how to read from a disk, but I don't have a disk drive. I could be confusing terminology, but I don't think I am. Here is the code I have for reading fr

  • Report using GL Hierarchy directly from a cube in crystal reports

    Hi, I am trying to build a crystal report showing GL account hierarchy ( a P n L report). When I am trying to source this field from the BW cube directly its not showing up on the report preview at all.  I built something similar with hierarchy using

  • How can i export (render) or view a composition without background

    I have a 3D moving object composition with a black background. I need to export only the object with no background.  Like the gray\white checkers background, that allows you to export only the object. So after that i can plant it in an editing softwa

  • Events 1863 and 2093 post 2003 Migration to 2008 R2

    I have migrated AD from a 2003 SBS SP2 server to a 2008 R2 SP1 server using the following article: http://technet.microsoft.com/en-us/library/dd379526.aspx That was 2 days ago, this morning I noticed the following events in the 2008 error log: Error

  • Can't get videos to sync with the ipod!

    I have a music video that i want to sync with my ipod, and i can already view the MV in itunes, it is already in my library, but when i try to copy manually the video into the ipod, it does not sync the video! only the song.... I have also tried sett