操作Blob型別的方法(zt)

jolly10發表於2008-05-27
轉自http://space.itpub.net/498744/viewspace-281097[@more@]

注:下列過程中的引數p_filename為外部檔名稱,p_name用於標識唯一的一行

1.建立目錄utl_dir用於檔案的匯入、匯出
create or replace directory utl_dir as 'd:';

2.給所有使用者賦予讀寫utl_dir的許可權
grant write,read on directory utl_dir to public;

3.建立測試表blob_test,其中列a為blob型別,b列在實際應用中可以是表的PK列
create table blob_test(a blob,b number);

4.將外部檔案插入blob列
CREATE OR REPLACE PROCEDURE insert_blob(p_name varchar2,p_filename varchar2) IS
i_blob BLOB;
i_file BFILE := BFILENAME('UTL_DIR',p_filename);
BEGIN
INSERT INTO blob_test VALUES (EMPTY_BLOB(),p_name)
RETURNING test INTO i_blob;

DBMS_LOB.FILEOPEN(i_file);
DBMS_LOB.LOADFROMFILE(i_blob, i_file, DBMS_LOB.GETLENGTH(i_file));
DBMS_LOB.FILECLOSE(i_file);

COMMIT;
END;

5.用外部檔案更新blob列
CREATE OR REPLACE PROCEDURE update_blob(p_name varchar2,p_filename varchar2) IS
i_blob BLOB;
i_file BFILE := BFILENAME('UTL_DIR',p_filename);
BEGIN
UPDATE blob_test SET test = EMPTY_BLOB() WHERE b = p_name
RETURNING test INTO i_blob;

DBMS_LOB.FILEOPEN(i_file);
DBMS_LOB.LOADFROMFILE(i_blob, i_file, DBMS_LOB.GETLENGTH(i_file));
DBMS_LOB.FILECLOSE(i_file);

COMMIT;
END;

6.用於檢視insert、update是否成功的語句
SELECT DBMS_LOB.GETLENGTH(test) FROM blob_test;

7.將資料庫中的blob列匯出為外部檔案
CREATE OR REPLACE PROCEDURE dump_blob (p_name varchar2,p_filename varchar2) IS
l_file UTL_FILE.FILE_TYPE;
l_buffer RAW(32767);
l_amount BINARY_INTEGER := 32767;
l_pos INTEGER := 1;
l_blob BLOB;
l_blob_len INTEGER;
BEGIN
SELECT test INTO l_blob FROM blob_test WHERE b = p_name;

l_blob_len := DBMS_LOB.GETLENGTH(l_blob);
l_file := UTL_FILE.FOPEN('UTL_DIR',p_filename,'wb', 32767);

WHILE l_pos < l_blob_len LOOP
DBMS_LOB.READ (l_blob, l_amount, l_pos, l_buffer);
UTL_FILE.PUT_RAW(l_file, l_buffer, TRUE);
l_pos := l_pos + l_amount;
END LOOP;

UTL_FILE.FCLOSE(l_file);

EXCEPTION
WHEN OTHERS THEN
IF UTL_FILE.IS_OPEN(l_file) THEN
UTL_FILE.FCLOSE(l_file);
END IF;
RAISE;
END;

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/271283/viewspace-1004677/,如需轉載,請註明出處,否則將追究法律責任。

相關文章