用oracle读取本地文件
首先要在oracle中创建文件夹,然后赋予相应的读写权限,然后数据库才能读取系统中的文件
--创建文件夹 并赋予权限给用户
create or replace directory DIRNAME as 'D:/skybook2';
grant read,write on directory DIRNAME as to USERNAME;
GRANT EXECUTE ON utl_file TO USERNAME;
创建成功可以查看一下
--查看系统所有创建的文件夹
select * from ALL_DIRECTORIES;
编写一个简单的读取文件的存储过程
create or replace procedure loadfiledata(p_path varchar2, --文件的路径 (上文中建立的文件名 DIRNAME)
p_filename varchar2 --文件的名字(如 text.txt, test.jsp)
) as
v_filehandle utl_file.file_type; --定义一个文件句柄
v_text varchar2(100); --存放文本
v_name test_loadfile.name%type;
v_addr_jd test_loadfile.addr_jd%type;
v_region test_loadfile.region%type;
v_firstlocation number;
v_secondlocation number;
v_totalinserted number;
begin
if (p_path is null or p_filename is null) then
goto to_end;
end if;
v_totalinserted:=0;
/*open specified file*/
v_filehandle:=utl_file.fopen(p_path,p_filename,'r');
loop
begin
utl_file.get_line(v_filehandle,v_text);----将文件写入v_text
exception
when no_data_found then
exit;
end ;
v_firstlocation:=instr(v_text,',',1,1);
v_secondlocation:=instr(v_text,',',1,2);
v_name:=substr(v_text,1,v_firstlocation-1);
v_addr_jd:=substr(v_text,v_firstlocation+1,v_secondlocation-v_firstlocation-1);
v_region:=substr(v_text,v_secondlocation+1);
/*插入数据库操作*/
insert into test_loadfile
values (v_name,v_addr_jd,v_region);
commit;
end loop;
<<to_end>>
null;
end loadfiledata;
注意:提醒大家千万要注意,操作文件一定要在oracle安装的服务器, 否则操作文件的时候会报错,而且很不容易找出问题所在。