1

I have a column in my oracle table with CLOB datatype. How do I store .txt file in this column and how can I retrieve the same file?

Below is the table definition

fileID  Number
logFile CLOB

Thanks in advance

Justin Cave
  • 227,342
  • 24
  • 367
  • 384
acadia
  • 2,619
  • 18
  • 55
  • 72

1 Answers1

9

Loading a file into a CLOB in PL/SQL is pretty easy-- you just need to use the DBMS_LOB.LoadCLOBFromFile procedure

CREATE DIRECTORY file_dir
    AS <<path on database server file system>>;

GRANT read, write
   ON file_dir
   TO your_user_name;

DECLARE
  l_src_file bfile := BFileName( 'FILE_DIR', <<name of file>> );
  l_dest_lob clob;

  l_dest_offset  integer := 1;
  l_src_offset   integer := 1;
  l_lang_context number := dbms_lob.default_lang_ctx;
  l_warning      number;
BEGIN
  dbms_lob.open( l_src_file, dbms_lob.lob_readonly );

  INSERT INTO some_table( fileID, logFile )
    VALUES( fileIDSeq.nextval, empty_clob() )
    RETURNING logFile 
         INTO l_dest_lob;

  dbms_lob.LoadCLOBFromFile( 
              dest_lob     => l_dest_lob,
              src_bfile    => l_src_file,
              amount       => dbms_lob.getLength( l_src_file ),
              dest_offset  => l_dest_offset,
              src_offset   => l_src_offset,
              bfile_csid   => dbms_lob.default_csid,
              lang_context => l_lang_context,
              warning      => l_warning );

  dbms_lob.close( l_src_file );
END;
/

Writing the file from the CLOB to the file system again is a bit more involved. I would use something like Tom Kyte's clob_to_file procedure

Justin Cave
  • 227,342
  • 24
  • 367
  • 384
  • You shouldn't just say this without explaining how to derive it "<>" definitely not "pretty easy". – Philip Rego Dec 22 '17 at 17:57
  • @PhilipRego - I'm not sure what you mean by "how to derive it". The `<>` can be any path you want, there is no "magic" path that you need to derive. It is wherever the files you want to load live on the server's file system. – Justin Cave Dec 22 '17 at 20:51