使用UTL_FILE在oracle中讀寫文本資料

來源:互聯網
上載者:User
Technorati 標籤: oracle

--以SYS使用者建立目錄dir_dump,檔案就儲存在這個目錄下
SQL> create directory dir_dump as '/data/cmssdb';
Directory created.
--授權對應的操作帳號讀和寫的許可權,這裡是operator
SQL> grant read on directory dir_dump to operator;
Grant succeeded.
SQL> grant write on directory dir_dump to operator;
Grant succeeded.
--以operator使用者登陸
SQL> connect operator/operation
Error accessing PRODUCT_USER_PROFILE
Warning:  Product user profile information not loaded!
You may need to run PUPBLD.SQL as SYSTEM
Connected.
--建立表BIBI,並加入測試資料
SQL> create table bibi(row_id int,row_name varchar2(10));
Table created.
SQL> insert into bibi values(1,'luochun');
1 row created.
SQL> insert into bibi values(2,'maihy');
1 row created.
SQL> commit;
Commit complete.
/*--該過程負責備份資料到DIR_DUMP目錄,名稱為bibi.csv
DECLARE lv_file_handle UTL_FILE.file_type;
BEGIN
lv_file_handle := UTL_FILE.FOPEN('DIR_DUMP','bibi.csv','a');
FOR x IN (SELECT ROW_ID,ROW_NAME FROM BIBI) LOOP
  UTL_FILE.PUT_LINE(lv_file_handle,x.ROW_ID || ',' || NVL(x.ROW_NAME,''));
END LOOP;
UTL_FILE.FCLOSE(lv_file_handle);
EXCEPTION WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SUBSTR(SQLERRM,1,200));
END;
/
*/
--過程完成,轉到DIR_DUMP目錄查看產生的檔案,資料已經產生
[oracle@qaserver oracle]$ cd /data/cmssdb
[oracle@qaserver cmssdb]$ cat bibi.csv
1,luochun
2,maihy
/*
--現在刪除BIBI資料,準備將備份的匯入
SQL> truncate table bibi;
Table truncated.
/*--這個過程負責讀取檔案,並匯入資料
DECLARE lv_file_handle UTL_FILE.file_type;
lv_row_text VARCHAR2(2000);
lv_row_id PLS_INTEGER;
lv_row_name VARCHAR2(50);
BEGIN
lv_file_handle := UTL_FILE.FOPEN('DIR_DUMP','bibi.csv','r');
LOOP
  BEGIN
   UTL_FILE.GET_LINE(lv_file_handle,lv_row_text);
   lv_row_id := SUBSTR(lv_row_text,1,INSTR(lv_row_text,',',1,1) - 1);
   lv_row_name := SUBSTR(lv_row_text,INSTR(lv_row_text,',',1,1) + 1);
   INSERT INTO BIBI VALUES(lv_row_id,lv_row_name);
  EXCEPTION
   WHEN NO_DATA_FOUND THEN
    EXIT;
  END;
END LOOP;
COMMIT;
UTL_FILE.FCLOSE(lv_file_handle);
EXCEPTION WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SUBSTR(SQLERRM,1,200));
END;
/
*/
--資料已經產生
SQL> SQL> SELECT * FROM BIBI;
    ROW_ID ROW_NAME
---------- --------------------
         1 luochun
         2 maihy
SQL>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.