将文本文件插入Oracle表中

来源:互联网 发布:js中国地图插件 编辑:程序博客网 时间:2024/06/01 11:55

--1、建立测试表
create table TA
(
  ID       INTEGER,
  FILENAME BLOB
);
--2、建立数据库目录Directories
create or replace directory XT_MRTMPDIR
  as 'E:/oracle/product/10.2.0/oradata/TempMRU';
--3、创建存储过程
create or replace procedure insert_txt(txt_dir varchar2,txt_name varchar2)
is
 txt_blob blob;
 txt_bfile bfile;
begin
  /*将通过empty_blob()函数将类型为blob的列初始化为空以便以后填充*/
  insert into ta values(1,empty_blob())
  return ta.filename into txt_blob;

  txt_bfile := bfilename(txt_dir,txt_name); --获得定位器指向的目录和文件
  if (dbms_lob.fileexists(txt_bfile)!=0) then --如果文件定位器指向的文件存在
    dbms_lob.fileopen(txt_bfile,dbms_lob.file_readonly); --打开目标文件

    /*将文件字节流数据加载到指定的LOB类型变量中*/
    dbms_lob.loadfromfile(txt_blob,txt_bfile,dbms_lob.getlength(txt_bfile));

    dbms_lob.fileclose(txt_bfile);--关闭文件
    commit;
    dbms_output.put_line('已经从'||txt_dir||'目录中读取了文本'||txt_name||'向表中插入');

  else--如果文件定位器指向的文件不存在
    dbms_output.put_line('文件没找到');
  end if;

  exception when others then
  dbms_output.put_line(sqlerrm);
end;

--4、在E:/oracle/product/10.2.0/oradata/TempMRU创建要插入的aa.txt和bb.csv文件

--5、调用存储过程
begin
insert_txt('XT_MRTMPDIR','aa.txt');
end;

原创粉丝点击