connect sys/password as sysdba
grant execute on UTL_FILE to public;
create directory filesdir as 'c:\oracle'; grant read on directory filesdir to public; grant write on directory filesdir to public;
connect hr/hr; create table names ( name varchar2(30) );
Kevin Tom Steve George
DECLARE line VARCHAR2(100); namesfile UTL_FILE.FILE_TYPE; BEGIN -- Syntax : FOPEN ( directory alias, filename, open mode) namesfile := UTL_FILE.FOPEN('FILESDIR','NAMES.TXT','R'); -- open in read mode LOOP -- read a line from NAMES.TXT -- NO_DATA_FOUND exception occurs when you reach end of file -- Syntax : GET_LINE( filename, variable , max length) UTL_FILE.GET_LINE(namesfile,line,100); insert into names values( line); -- insert into NAMES table END LOOP; EXCEPTION WHEN OTHERS THEN UTL_FILE.FCLOSE(namesfile); -- close file WHEN OTHERS THEN dbms_output END;
select * from names;
DECLARE JOBSFILE UTL_FILE.FILE_TYPE; -- TAKE ALL JOB TITLES FROM JOBS CURSOR JOBSCUR IS SELECT JOB_TITLE FROM JOBS ORDER BY JOB_TITLE; BEGIN -- OPEN FILE FOR WRITING JOBSFILE := UTL_FILE.FOPEN('FILESDIR','JOBS.TXT','W'); -- TAKE ONE RECORD FROM CURSOR FOR REC IN JOBSCUR LOOP UTL_FILE.PUT_LINE(JOBSFILE, REC.JOB_TITLE); -- WRITE INTO FILE END LOOP; UTL_FILE.FCLOSE(JOBSFILE); -- CLOSE FILE EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE( 'ERROR -->' || SQLERRM); END;