Export BLOB Data to File in PL/SQL: Complete Guide

In PL/SQL, you can use the FILEUTIL subprogram in the DBMS_LOB package to export BLOB data to a file. Here is an example code:

DECLARE
   l_blob BLOB;
   l_blob_len INTEGER;
   l_dest_offset INTEGER := 1;
   l_src_offset INTEGER := 1;
   l_warning INTEGER;
   l_file UTL_FILE.FILE_TYPE;
BEGIN
   -- 从数据库中获取BLOB数据
   SELECT blob_column INTO l_blob FROM table_name WHERE condition;

   -- 获取BLOB数据的长度
   l_blob_len := DBMS_LOB.getlength(l_blob);

   -- 打开一个文件句柄
   l_file := UTL_FILE.fopen('DIRECTORY_PATH', 'output_file.txt', 'wb', 32767);

   -- 将BLOB数据写入文件
   DBMS_LOB.FILEOPEN(l_blob);
   DBMS_LOB.loadblobfromfile(dest_lob => l_blob,
                              src_lob => l_blob,
                              amount => l_blob_len,
                              dest_offset => l_dest_offset,
                              src_offset => l_src_offset);
   DBMS_LOB.FILECLOSE(l_blob);

   -- 关闭文件句柄
   UTL_FILE.fclose(l_file);

   DBMS_OUTPUT.put_line('BLOB data exported successfully!');
EXCEPTION
   WHEN OTHERS THEN
      DBMS_OUTPUT.put_line('Error: ' || SQLERRM);
END;

In the code above, retrieve BLOB data from the database into the variable l_blob, and then write it to a file. Make sure to replace DIRECTORY_PATH with the actual directory path and output_file.txt with the actual output file name in the code, and modify the SELECT statement as needed to retrieve data from the correct table.

bannerAds