Oracle中BLOB是用來存儲圖片、文件等大數據對象的。
本文是一個Ruby讀寫Oracle的BLOB的例子,經過OCI8操做Oracle的存儲過程html
一、建表sql
CREATE TABLE "T_IMAGE" ( "ID" NUMBER(11) GENERATED BY DEFAULT AS IDENTITY NOT NULL , "IMG" BLOB NULL )
二、寫blob的存儲過程ruby
create or replace PROCEDURE P_WRITE_IMAGE ( I_PID IN NUMBER , B_IMG IN BLOB ) AS blob_temp BLOB; copy_amount integer; BEGIN insert into T_IMAGE values(I_PID,empty_blob()); commit; select IMG into blob_temp FROM T_IMAGE where id = I_PID FOR UPDATE; copy_amount := dbms_lob.getlength(B_IMG); dbms_lob.copy(blob_temp, B_IMG, copy_amount); commit; END P_WRITE_IMAGE;
三、讀blob的存儲過程oracle
CREATE OR REPLACE PROCEDURE "P_READ_IMAGE" ( V_IMG_ID IN NUMBER, CUR_RESULT OUT SYS_REFCURSOR ) AS BEGIN OPEN CUR_RESULT FOR SELECT ID,IMG FROM T_IMAGE WHERE ID=V_IMG_ID ; END;
四、ruby寫圖片操做fetch
require 'oci8' h_conn = OCI8.new(DB_USER, DB_PASSWORD, DB_SERVER) s_photo_full_path = "~/111.jpg" begin cursor = h_conn.parse('begin P_WRITE_IMAGE ( :photo_id, :photo ); end;') lob_photo = OCI8::BLOB.new(h_conn, File.read(s_photo_full_path, :mode => 'rb')) cursor.bind_param(':photo_id', nil, Fixnum) cursor.bind_param(':photo', lob_photo ) cursor.exec() rescue OCIError puts '-'*80 puts "Code: " + $!.code.to_s puts "Desc: " + $!.message puts '-'*80 end
五、ruby讀圖片操做
大數據
require 'oci8' h_conn = OCI8.new(DB_USER, DB_PASSWORD, DB_SERVER) s_photo_target_path = "~/222.jpg" photo_id = 1 begin cursor = h_conn.parse('begin P_READ_IMAGE( :img_id, :list ); end;') cursor.bind_param(':img_id', photo_id) cursor.bind_param(':list', nil, OCI8::Cursor) cursor.exec() ret_cursor = cursor[':list'] puts ret_cursor.getColNames.join(",") while row = ret_cursor.fetch() puts row[0] File.open(s_photo_target_path, 'wb') do |f| f.write(row[1].read) end break; end rescue OCIError puts '-'*80 puts "Code: " + $!.code.to_s puts "Desc: " + $!.message puts '-'*80 end
參考教程ui
http://www.oracle.com/technetwork/cn/tutorials/rubyrails-095981-zhs.htmlcode