Create
directory让我们可以在Oracle数据库中灵活的对文件进行读写操作,极大的提高了Oracle的易用性和可扩展性。
其语法为:
create or replace directory exp_dir as '/tmp';
目录创建以后,就可以把读写权限授予特定用户,例如:
grant read, write on directory exp_dir to eygle;
此时用户eygle就拥有了对该目录的读写权限。
例如:
当用SCOTT进行目录创建的时候,首先应该赋给SCOTT创建目录的权限,如果没有则会报一下错误
SQL> create or replace directory
MY_DIR as 'd:\test';
create or replace directory
MY_DIR as 'd:\test'
ORA-01031: 权限不足
SQL> GRANT CREATE ANY DIRECTORY TO
scott;--授权给SCOTT用户创建目录权限
Grant succeeded
SQL>create or replace directory
MY_DIR as
'd:\test';--创建了一个目录名为'MY_DIR'的目录,他的路径是'd:\test'
Directory created.
SQL>select * from all_directories;--查看创建的目录
OWNER DIRECTORY_NAME DIRECTORY_PATH
SYS MY_DIR d:\test
SQL> drop directory my_dir;--删除目录
Directory dropped
写入文件:
SQL> DECLARE
2 filehandle utl_file.file_type;
3 begin
4 filehandle :=
utl_file.fopen('MY_DIR','test.txt','w');
5 utl_file.put_line(filehandle,'test 1 write one.');
6 utl_file.put_line(filehandle,'你好!');
7 utl_file.fclose(filehandle);
8 end;
9 /
PL/SQL procedure successfully completed
读出文件:
SQL> set serveroutput on
SQL> DECLARE
2 filehandle utl_file.file_type;
3 filebuffer
varchar2(500);
4 begin
5 filehandle :=
utl_file.fopen('MY_DIR','test.txt','R');
6 utl_file.get_line(filehandle,filebuffer);
7 dbms_output.put_line(filebuffer);
8 utl_file.get_line(filehandle,filebuffer);
9 dbms_output.put_line(filebuffer);
10 utl_file.fclose(filehandle);
11 end;
12 /
test 1 write one.
你好!
PL/SQL procedure successfully completed
用BFILE读出整个文件:
SQL> declare
2 v_content
varchar2(100);
3 v_bfile bfile;
4 amount int;
5 offset int:=1;
6 begin
7 v_bfile:=bfilename('MY_DIR','test.txt');
8 amount:=dbms_lob.getlength(v_bfile);
9 dbms_lob.fileopen(v_bfile);
10 dbms_lob.read(v_bfile,amount,offset,v_content);--读b_fil里从offset开始读amount个字节到v_content里
11 dbms_lob.fileclose(v_bfile);
12 dbms_output.put_line(v_content);
13 end;
14 /