天天看點

ORACLE之 通路 CLOB

通路 CLOB

CLOB 用于存放大批量的文本資料。所允許的最大資料長度為 4G 位元組。在 oracle8 版本以前使用 LONG 存放大批量文本資料,且最大長度為 2G 位元組。

示例

建立包含 CLOB 列的表

create table lob_example
(
  serial number(6) primary key,
  p_name varchar2(10),
  p_resume clob
);
           

初始化 CLOB 列

使用 EMPTY_CLOB() 初始化 CLOB 列。該函數沒有提供任何資料,但是配置設定了 LOB 定位符。

insert into lob_example values(1, 'Linchong', empty_clob());
insert into lob_example values(2, 'Songjiang', empty_clob());
           

更新 CLOB 列的資料

如果要更新 CLOB 列的資料,那麼在檢索 CLOB 列時必須使用帶有 FOR UPDATE 子句。為 CLOB 列追加資料可以使用包 DBMS_LOB 中的 WRITE 和 WRITEAPPEND。

declare
  lob_loc clob;
  text varchar2(200);
  amount int;
  offset int;
begin
  select p_resume into lob_loc from lob_example where serial=&serial for update;
  offset := dbms_lob.getlength(lob_loc)+1;
  text := '&resume';
  amount := length(text);
  dbms_lob.write(lob_loc, amount, offset, text);
  commit;
end;
           

讀取 CLOB 列的内容

為了讀取 CLOB 列的所有資料,應該使用循環方式進行處理。讀取 CLOB 列的資料,使用包 DBMS_LOB.READ

declare
  lob_loc clob;
  buff varchar2(200);
  amount int;
  offset int;
begin
  select p_resume into lob_loc from lob_example where serial=&serial;
  offset := 11;
  amount := dbms_lob.getlength(lob_loc);
  dbms_lob.read(lob_loc, amount, offset, buff);
  dbms_output.put_line(buff);
end;
           

将文本檔案内容寫入到  CLOB 列

在開發 PL/SQL 應用程式時,使用過程 LOADFROMFILE 或 LOADCLOBFROMFILE。為了避免字元集問題,建議使用 LOADCLOBFROMFILE。

建立 BFILE 與本地磁盤關聯的目錄

create or replace directory ORCL_DIR as 'D:\tools';
           
declare
  lob_loc clob;
  fileloc bfile;
  amount int;
  src_offset int := 1;
  dest_offset int := 1;
  csid int := 0;
  lc int := 0;
  warning int;
begin
  fileloc := bfilename('ORCL_DIR', 'song.txt');
  dbms_lob.fileopen(fileloc, 0);
  amount := dbms_lob.getlength(fileloc);
  select p_resume into lob_loc from scott.lob_example where serial=2 for update;
  dbms_lob.loadclobfromfile(lob_loc, fileloc, amount, dest_offset, src_offset, csid, lc, warning);
  dbms_lob.fileclose(fileloc);
  commit;
end;
           

将 CLOB 列資料寫入到文本檔案

使用包 DBMS_LOB 讀取 CLOB 列的資料,并且還需要使用 UTL_FILE 包建立文本檔案并寫入内容。

declare
  lob_loc clob;
  amount int;
  offset int := 1;
  buff varchar2(2000);
  handle utl_file.file_type;
begin
  select p_resume into lob_loc from scott.lob_example where serial=&serial;
  amount := dbms_lob.getlength(lob_loc);
  dbms_lob.read(lob_loc, amount, offset, buff);
  handle := utl_file.fopen('ORCL_DIR', 'lc.txt', 'w', 2000);
  utl_file.put_line(handle, buff);
  utl_file.fclose(handle);
end;