oracle中utl_file包读写文件操作实例学习
关东大先生演员表,河道清淤机械,洞口县人民政府
在oracle中utl_file包提供了一些操作文本文件的函数和过程,学习了一下他的基本操作
1.创建directory,并给用户授权
--创建directory
create or replace directory testfile as '/home/oracle/zxx/test';
--给用户授权
grant read, write on directory testfile to zxx;
详细介绍
http://download.oracle.com/docs/cd/b19306_01/appdev.102/b14258/u_file.htm
2.写入操作
---测试写入
declare
filehandle utl_file.file_type; --句柄
begin
filehandle := utl_file.fopen('testfile','hello.txt','w'); --打开文件
utl_file.put_line(filehandle,'hello oracle!');--写入一行记录
utl_file.put_line(filehandle,'hello world!');
utl_file.put_line(filehandle,'你好,胖子!');
utl_file.fclose(filehandle);--关闭句柄
end;
备注:
fopen有一个参数max_linesize,下面是原文解释
maximum number of characters for each line, including the newline character, for this file (minimum value 1, maximum value 32767). if unspecified, oracle supplies a default value of 1024.
3.读取操作
--测试读取
set serveroutput on;
declare
filehandle utl_file.file_type;
filebuffer varchar2(500);
begin
filehandle := utl_file.fopen('testfile','hello.txt','r');
if utl_file.is_open(filehandle) then
dbms_output.put_line('file is open!');
end if;
loop
begin
utl_file.get_line(filehandle,filebuffer);
dbms_output.put_line(filebuffer);
exception
when no_data_found then
exit ;
when others then
dbms_output.put_line('exception1:'||substr(sqlerrm, 1, 100)) ;
end;
end loop;
utl_file.fclose(filehandle);
if utl_file.is_open(filehandle) then
dbms_output.put_line('file is open!');
else
dbms_output.put_line('file is close!');
end if;
utl_file.fcopy('testfile', 'hello.txt', 'testfile', 'hello.dat');--复制
utl_file.fcopy('testfile', 'hello.txt', 'testfile', 'hello2.dat');
utl_file.fcopy('testfile', 'hello.txt', 'testfile', 'hello.xls');
utl_file.frename('testfile','hello.xls','testfile','frenamehello.xls',true);--重命名
utl_file.fremove('testfile', 'hello2.dat');--删除文件
exception
when others then
dbms_output.put_line('exception2:'||substr(sqlerrm, 1, 100)) ;
end;
4.判断文件是否存在(读,重命名,复制,删除都要判断文件是否存在)
--判断文件是否存在
declare
ex boolean;--文件是否存在
flen number;--文件长度? 这个地方不知道怎么理 (原文 file_length the length of the file in bytes. null if file does not exist.)
bsize number;--文件大小
begin
utl_file.fgetattr('testfile', 'hello.txt', ex, flen, bsize);
if ex then
dbms_output.put_line('file exists');
else
dbms_output.put_line('file does not exist');
end if;
dbms_output.put_line('file length: ' || to_char(flen));
dbms_output.put_line('block size: ' || to_char(bsize));
end fgetattr;
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!!
点击进行留言回复
相关文章:
-
-
-
快速向表插入大量数据
当需要对一个非常大的表INSERT的时候,会消耗非常多的资源,因为update表的时候,oracle需要生成 redo log和undo log;此时最...
[阅读全文]
-
-
-
Oracle入门学习五
学习视频: https://www.bilibili.com/video/BV1tJ411r7EC?p=55 数据的完整性:保证插入表格的数据必须正确。...
[阅读全文]
-
Oracle入门学习六
事务:把一组操作看做一个工作单元,要么都执行,要么都不执行。dml操作才有事务,查询没有事务。 开始事务:从上一次的事务结束之后,从第一次dml操作,就...
[阅读全文]
-
-
-
Oracle入门学习一
oracle的安装,用户授权,表格操作,数据类型,ddl表格,dml数据。 下一篇:Oracle入门学习二 学习视频:https://www.bilib...
[阅读全文]
-
Oracle入门学习二
上一篇:Oracle入门学习一 学习视频:https://www.bilibili.com/video/BV1tJ411r7EC?p=15 算术运算符:...
[阅读全文]
网友评论