Oracle中BLOB是用来存储图片、文件等大数据对象的。
本文是一个Ruby读写Oracle的BLOB的例子,通过OCI8操作Oracle的存储过程
1、建表
CREATE TABLE "T_IMAGE" ( "ID" NUMBER(11) GENERATED BY DEFAULT AS IDENTITY NOT NULL , "IMG" BLOB NULL )
2、写blob的存储过程
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;
3、读blob的存储过程
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;
4、ruby写图片操作
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
5、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
参考教程
http://www.oracle.com/technetwork/cn/tutorials/rubyrails-095981-zhs.html
http://ruby-oci8.rubyforge.org/en/FAQ.html