Wednesday, November 18, 2009

Load image from directory to oracle table (blob)

Load image from directory to oracle table
==============================
SQL>
SQL> CONN / AS SYSDBA
Connected.
SQL>
SQL> grant dba to halim2 identified by halim2;
SQL> Conn halim2/halim2
SQL> create directory halim_blob as 'D:\halim_blob_dir';
Directory created.
SQL> CREATE TABLE image_table (
dname VARCHAR2(30), -- directory name
sname VARCHAR2(30), -- subdirectory name
fname VARCHAR2(30), -- file name
iblob BLOB)
/
Table created.

SQL> CREATE OR REPLACE PROCEDURE halim_load_image_file (
dir_name VARCHAR2,
sub_dir_name VARCHAR2,
file_name VARCHAR2
) IS
source_file BFILE;
destenation_file BLOB;
length_file BINARY_INTEGER;
BEGIN
source_file := BFILENAME ('HALIM_BLOB', file_name);

-- insert a NULL record to lock
INSERT INTO image_table
(dname, sname, fname, iblob
)
VALUES (dir_name, sub_dir_name, file_name, EMPTY_BLOB ()
)
RETURNING iblob
INTO destenation_file;

-- lock record
SELECT iblob
INTO destenation_file
FROM image_table
WHERE dname = dir_name AND sname = sub_dir_name AND fname = file_name
FOR UPDATE;

-- open the file
DBMS_LOB.fileopen (source_file, DBMS_LOB.file_readonly);
-- determine length
length_file := DBMS_LOB.getlength (source_file);
-- read the file
DBMS_LOB.loadfromfile (destenation_file, source_file, length_file);

-- update the blob field
UPDATE image_table
SET iblob = destenation_file
WHERE dname = dir_name AND sname = sub_dir_name AND fname = file_name;

-- close file
DBMS_LOB.fileclose (source_file);
END halim_load_image_file;
/
Procedure created.
-----------image load by procedure
SQL> EXEC halim_load_image_file('HALIM_BLOB','Image_test','c .jpg');
PL/SQL procedure successfully completed.
SQL> SELECT *
FROM image_table;
SP2-0678: Column or attribute type can not be displayed by SQL*Plus
SQL>
SQL>
----------image load by sql statement
SQL> DECLARE
image_file BLOB;
BEGIN
SELECT iblob
INTO image_file
FROM image_table;

DBMS_OUTPUT.put_line (DBMS_LOB.getlength (image_file));
END;
/
PL/SQL procedure successfully completed.
SQL> set serveroutput on
SQL>
SQL> ed
Wrote file afiedt.buf
DECLARE
image_file BLOB;
BEGIN
SELECT iblob
INTO image_file
FROM image_table;
DBMS_OUTPUT.put_line (DBMS_LOB.getlength (image_file));
END;
/

PL/SQL procedure successfully completed.
SQL>
SQL>
SQL> exit

No comments: