Oracle讀寫文件操作相信大家都不陌生,下面就為您介紹Oracle讀寫文件bfilename的實例,希望對您學習Oracle讀寫文件方面能有所幫助。
Create directory讓我們可以在Oracle數據庫中靈活的對文件進行讀寫操作,極大的提高了Oracle的易用性和可擴展性。
其語法為:
CREATE [OR REPLACE] DIRECTORY directory AS 'pathname';
本案例具體創建如下:
create or replace directory exp_dir as '/tmp';
目錄創建以後,就可以把讀寫權限授予特定用戶,具體語法如下:
GRANT READ[,WRITE] ON DIRECTORY directory TO username;
例如:
grant read, write on directory exp_dir to eygle;
此時用戶eygle就擁有了對該目錄的讀寫權限。
讓我們看一個簡單的測試:
- SQL> create or replace directory UTL_FILE_DIR as '/opt/Oracle/utl_file';
- Directory created.SQL> declare
- fhandle utl_file.file_type;
- begin
- fhandle := utl_file.fopen('UTL_FILE_DIR', 'example.txt', 'w');
- utl_file.put_line(fhandle , 'eygle test write one');
- utl_file.put_line(fhandle , 'eygle test write two');
- utl_file.fclose(fhandle);
- end;
- /
- PL/SQL procedure successfully completed.
- SQL> !
- [oracle@jumper 9.2.0]$ more /opt/Oracle/utl_file/example.txt
- eygle test write one
- eygle test write two
- [Oracle@jumper 9.2.0]$
類似的我們可以通過utl_file來讀取文件:
- SQL> declare
- fhandle utl_file.file_type;
- fp_buffer varchar2(4000);
- begin
- fhandle := utl_file.fopen ('UTL_FILE_DIR','example.txt', 'R');
- utl_file.get_line (fhandle , fp_buffer );
- dbms_output.put_line(fp_buffer );
- utl_file.get_line (fhandle , fp_buffer );
- dbms_output.put_line(fp_buffer );
- utl_file.fclose(fhandle);
- end;
- /
- eygle test write one
- eygle test write two
- PL/SQL procedure successfully completed.
可以查詢dba_directorIEs查看所有directory.
- SQL> select * from dba_directorIEs;
- OWNER DIRECTORY_NAME DIRECTORY_PATH------------------------------ ------------------------------ ------------------------------
- SYS UTL_FILE_DIR /opt/Oracle/utl_file
- SYS BDUMP_DIR /opt/Oracle/admin/conner/bdump
- SYS EXP_DIR /opt/Oracle/utl_file
可以使用drop directory刪除這些路徑.
- SQL> drop directory exp_dir;Directory droppedSQL> select * from dba_directorIEs;OWNER DIRECTORY_NAME DIRECTORY_PATH------------------------------ ------------------------------ ------------------------------SYS UTL_FILE_DIR /opt/oracle/utl_fileSYS BDUMP_DIR /opt/Oracle/admin/conner/bdump
- create or replace directory USER_DIR as 'E:\PLSQL\310\';
- DECLARE
- v_content VARCHAR2(1800);
- v_bfile BFILE;
- amount INT;
- offset INT :=1;
- BEGIN
- v_bfile := bfilename('USER_DIR','test.TXT'); -- 注意這裡的 User_dir 對應上面已經創建好啦的目錄
- amount :=DBMS_LOB.getlength(v_bfile);
- DBMS_LOB.OPEN(v_bfile);
- DBMS_LOB.READ(v_bfile,amount,offset,v_content);
- DBMS_LOB.close(v_bfile);
- DBMS_OUTPUT.PUT_LINE(v_content);
- END;