我正在使用以下功能从目录中读取文件:
CREATE OR REPLACE FUNCTION loadBlobFromFile(p_file_name VARCHAR2) RETURN BLOB AS
dest_loc BLOB := empty_blob();
src_loc BFILE := BFILENAME('TMT', 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));
exception
when DBMS_LOB.operation_failed
then
return empty_blob();
-- Close lob objects
DBMS_LOB.CLOSE(dest_loc);
DBMS_LOB.CLOSE(src_loc);
-- Return temporary LOB object
RETURN dest_loc;
END loadBlobFromFile;
/
我用
调用该函数select loadBlobFromFile('TESTl.doc') from dual;
当文件存在于目录中时,我得到了该文件。当文件不存在时,我得到空的Blob。
现在还有最后一个问题。当文件的大小为0字节时,我收到一个错误。
有人可以帮助我用异常改进函数并在dbms_lob.open失败时返回empty_blob()吗?
非常感谢你!
答案 0 :(得分:0)
添加这样的例外。
-- Open temporary lob
DBMS_LOB.OPEN(dest_loc, DBMS_LOB.LOB_READWRITE);
begin
-- Load binary file into temporary LOB
DBMS_LOB.LOADFROMFILE(
dest_lob => dest_loc
, src_lob => src_loc
, amount => DBMS_LOB.getLength(src_loc));
exception
when dbms_lob.operation_failed
then
return empty_blob();
end;
..rest of your code.
答案 1 :(得分:0)
我找到了解决方案。 这是我的最终代码,得到了帮助 http://www.toadworld.com/KNOWLEDGE/KnowledgeXpertforOracle/tabid/648/TopicID/DLP1/Default.aspx
功能代码:
CREATE OR REPLACE FUNCTION loadBlobFromFile(p_file_name VARCHAR2) RETURN BLOB AS
dest_loc BLOB := empty_blob();
src_loc BFILE := BFILENAME('Directoryname', p_file_name);
BEGIN
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));
exception
when DBMS_LOB.operation_failed --Wenn die Datei nicht vorhanden ist
then
DBMS_LOB.CLOSE(src_loc);
return empty_blob();
when DBMS_LOB.INVALID_ARGVAL --Wenn die Datei 0 KB gross ist.
then
DBMS_LOB.CLOSE(dest_loc);
DBMS_LOB.CLOSE(src_loc);
return empty_blob();
END;
-- Close lob objects
DBMS_LOB.CLOSE(dest_loc);
DBMS_LOB.CLOSE(src_loc);
-- Return temporary LOB object
RETURN dest_loc;
END loadBlobFromFile;
/
调用该函数:
select loadBlobFromFile('test.doc') from dual;
格尔茨