oracle 操作bfile和blob

来源:互联网 发布:数据平台有哪些 编辑:程序博客网 时间:2024/05/22 15:22
 
--搞定big objects
--author:shine
--准备
--创建文件夹,授权
/*conn system/manager;
create directory test as 'D:/test';
grant read on direcotry test to scott;
conn scott/tiger;*/
create table test2
(
tid int,
t_file bfile,
t_lob blob
)
--BFILE
--write bfile
insert into test2(tid,t_file)  
values(1,bfilename('TEST','/stuinfo.txt'));
commit;
--read bfile
declare
  v_file bfile;
  v_str raw(2000);
  v_amount int default 1000;
begin
  select t_file into v_file from test2 where tid=1;  --从database中读出 (1.映射)
--v_file:=bfilename('TEST','/stuinfo.txt');  --直接从文件夹中取出
  dbms_lob.open(v_file,dbms_lob.file_readonly); --(2.开文件)
  dbms_lob.read(v_file,v_amount,1,v_str); --(3.读出)
  dbms_output.put_line(utl_raw.cast_to_varchar2(v_str));
  dbms_lob.fileclose(v_file); --(4.关文件)
end;
--BLOB
--write blob
declare
  v_blob blob;
  v_bfile bfile;
begin
  insert into test2(tid,t_lob)
  values(4,empty_blob())
  return t_lob into v_blob;
  v_bfile:=bfilename('TEST','/stuinfo.txt'); --(1.做个v_blob引用和v_file映射)
  dbms_lob.open(v_bfile,dbms_lob.file_readonly); --(2.开文件)
  dbms_lob.loadfromfile(v_blob,v_bfile,dbms_lob.getlength(v_bfile)); (3.把文件载入blob)
  dbms_lob.fileclose(v_bfile); (4.关文件)
  commit;
end;
--read blob
declare
  v_blob blob;
  v_amount int default 2000;
  v_raw raw(3000);
begin
  select t_lob into v_blob from test2 where tid=4; -- (1.取出blob)
  dbms_lob.read(v_blob,v_amount,1,v_raw); --(2.读blob)
  dbms_output.put_line(utl_raw.cast_to_varchar2(v_raw));
end;
select * from test2;
--CLOB和BLOB差不多只不过在读了时候,不用转了
­
总结一哈:
1、blob和bfile都可以读写large objects
2、bfile写容易(直接写),读难(要开文件啊,关文件..)
3、blob写难(要把bfile转到blob中才能写),读容易(和bfile无关,直接读)