在oracle9i,如何在PL/SQL中讀寫文件
2024-08-29 13:30:45
供稿:網友
網站運營seo文章大全提供全面的站長運營經驗及seo技術!
pl/sql 3.3以上的版本中,utl_file包允許用戶通過pl/sql讀寫操作系統文件。如下:
declare
file_handle utl_file.file_type;
begin
file_handle := utl_file.fopen('tmp', '文件名', 'w',[1-32767]);
--四個參數:目錄,文件名,打開方式,最大行數(默認為2000)
utl_file.putf(file_handle, '寫入的信息/n');
utl_file.fclose(file_handle);
exception
when utl_file.invalid_path then
raise_application_error(-20000, 'error: invalid path for file or path not in init.ora.');
end;
putf()過程用來以指定格式把文本寫入一個文件
put_line()過程把一個指定的字符串寫入文件并在文件中開始新的一行
9i中函數說明:
utl_file.fopen (
location in varchar2,
filename in varchar2,
open_mode in varchar2,
max_linesize in binary_integer)
return file_type;
parameters description
location (in) the directory location of the source file, a directory_name from the all_directories view (case sensitive)
filename file name, including extension (file type), without directory path. in unix,the filename cannot end with /.
一個使用文件的測試
1、用sys用戶登錄到數據庫(ora9i):conn sys/[email protected] as sysdba
2、在sqlplus中運行create or replace directory tmp as 'd:/testtmp';
在sqlplus中運行grant read on directory tmp to public
3、在scott用戶下建立存儲過程如:preadfiletest
create or replace procedure preadfiletest
(fpath in string,fname in string,max_num in number)
is
file_handle utl_file.file_type;
text_buffer string(1000);
line_num number;
begin
dbms_output.put_line('input path='||fpath);
dbms_output.put_line('input filename='||fname);
line_num :=0;
begin
file_handle := utl_file.fopen(fpath,fname,'r',max_num);
loop
line_num:= line_num + 1;
utl_file.get_line(file_handle,text_buffer);
dbms_output.put_line('line'||line_num||' : '||text_buffer);
end loop;
exception
when no_data_found then
return;
when utl_file.invalid_path then
dbms_output.put_line('invalid path');
when utl_file.invalid_mode then
dbms_output.put_line('invalid mode');
when utl_file.invalid_filehandle then
dbms_output.put_line('invalid filehandle');
when utl_file.invalid_operation then
dbms_output.put_line('invalid operation');
when utl_file.read_error then
dbms_output.put_line('read error');
when utl_file.write_error then
dbms_output.put_line('write error');
when utl_file.internal_error then
dbms_output.put_line('internal error');
when others then
dbms_output.put_line(sqlerrm);
end;
exception
when others then
dbms_output.put_line('other error='||sqlerrm);
end preadfiletest;
4、在sqlplus中運行set serveroutput on
5、exec preadfiletest('tmp','a.txt','r')
6、正常輸出
小結:在9i中可以不在init.ora中增加utl_file_dir目錄,而是在sys用戶下創建一個directory目錄(實際上是在sys用戶下的dir$表中增加一個對應的os_path),然后將對該directory對象的讀/寫操作的權限grant給public。