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>