Categories
BLOB Load File Into BLOB Oracle PL/SQL

Loading a File Into a BLOB Object in Oracle

Loading a file into a BLOB object in Oracle is easy. All we need to do is use the DBMS_LOB package to load the file into a temporary LOB object. This is demonstrated in the following example.

This example assumes that you have a directory object set up where the files are stored. In this example the following object is used:

CREATE DIRECTORY FILEUPLOADS AS '/home_new/dmt/public_html/fileuploads';

Use the following function to load a file based on the filename parameter and return the BLOB reference for processing:


CREATE OR REPLACE FUNCTION loadBlobFromFile(p_file_name VARCHAR2) RETURN BLOB AS
  dest_loc  BLOB := empty_blob();
  src_loc   BFILE := BFILENAME('FILEUPLOADS', p_file_name);
BEGIN
  -- Open source binary file from OS
  DBMS_LOB.OPEN(src_loc, DBMS_LOB.LOB_READONLY);
  
  -- Create temporary LOB object
  DBMS_LOB.CREATETEMPORARY(
        lob_loc => dest_loc
      , cache   => true
      , dur     => dbms_lob.session
  );
    
  -- Open temporary lob
  DBMS_LOB.OPEN(dest_loc, DBMS_LOB.LOB_READWRITE);
  
  -- Load binary file into temporary LOB
  DBMS_LOB.LOADFROMFILE(
        dest_lob => dest_loc
      , src_lob  => src_loc
      , amount   => DBMS_LOB.getLength(src_loc));
  
  -- Close lob objects
  DBMS_LOB.CLOSE(dest_loc);
  DBMS_LOB.CLOSE(src_loc);
  
  -- Return temporary LOB object
  RETURN dest_loc;
END loadBlobFromFile;
/

Easy as that.

Categories
CHAR Datatype Oracle VARCHAR2

Oracle VARCHAR2(1) vs CHAR(1)?

Well, minimum size for both Oracle datatypes is 1 byte. So in terms of storage, they’ll both consume either null or 1 byte in storage space. So, when declaring a character datatype with a length of 1, it doesn’t really matter which one you use. The rules change when the length is greater than 1 though.

This is because CHAR is a fixed character data, so values held in this datatype is always RPAD’ed with blanks. Storing character data as VARCHAR2 will save space on, not just the character field, but any indexes that reference it.

As a personal preference, I always use VARCHAR2. The most important practice though is to be consistent. For example, if you use CHAR for a 1 byte character datatype and VARCHAR2 for everything else, then stick with it throughout your whole database.