Using PL/SQL how do you I get a file's contents in to a blob?

后端 未结 2 1868
执念已碎
执念已碎 2020-12-29 17:04

I have a file. I want to get its contents into a blob column in my oracle database or into a blob variable in my PL/SQL program. What is the best way to do that?

相关标签:
2条回答
  • 2020-12-29 17:12

    Depends a bit on your environment. In Java you could do it something like this...

    // Need as OracleConnection in mConnection
    
    // Set an EMPTY_BLOB()
    String update = "UPDATE tablename"+
                    " SET   blob_column = EMPTY_BLOB()"+
                    " WHERE  ID = "+id;
    CallableStatement stmt = mConnection.prepareCall(update);
    stmt.executeUpdate();
    
    // Lock the row FOR UPDATE
    String select    = "BEGIN " +
                            "  SELECT " + blob_column
                            "  INTO ? " +
                            "  FROM " + tablename +
                            "  WHERE  ID = '" + id + "'" +
                            "  FOR UPDATE; " +
                            "END;";
    
    stmt = mConnection.prepareCall(select);
    stmt.registerOutParameter(1, java.sql.Types.BLOB);
    stmt.executeUpdate();
    
    BLOB blob = (BLOB) stmt.getBlob(1);
    OutputStream bos = blob.setBinaryStream(0L);
    FileInputStream fis = new FileInputStream(file);
    //  Code needed here to copy one stream to the other
    fis.close();
    bos.close();
    stmt.close();
    
    mConnection.commit();
    

    But it really depends what environment / tools you're using. More info needed.

    0 讨论(0)
  • 2020-12-29 17:32

    To do it entirely in PL/SQL, the file would need to be on the server, located in a directory which you'd need to define in the database. Create the following objects:

    CREATE OR REPLACE DIRECTORY
        BLOB_DIR
        AS
        '/oracle/base/lobs'
    /
    
    
    
    CREATE OR REPLACE PROCEDURE BLOB_LOAD
    AS
    
        lBlob  BLOB;
        lFile  BFILE := BFILENAME('BLOB_DIR', 'filename');
    
    BEGIN
    
        INSERT INTO table (id, your_blob)
            VALUES (xxx, empty_blob())
            RETURNING your_blob INTO lBlob;
    
        DBMS_LOB.OPEN(lFile, DBMS_LOB.LOB_READONLY);
    
        DBMS_LOB.OPEN(lBlob, DBMS_LOB.LOB_READWRITE);
    
        DBMS_LOB.LOADFROMFILE(DEST_LOB => lBlob,
                              SRC_LOB  => lFile,
                              AMOUNT   => DBMS_LOB.GETLENGTH(lFile));
    
        DBMS_LOB.CLOSE(lFile);
        DBMS_LOB.CLOSE(lBlob);
    
        COMMIT;
    
    END;
    /
    
    0 讨论(0)
提交回复
热议问题