Ruby通过OCI8操作Oracle存储BLOB

本文介绍如何使用Ruby编程语言与Oracle数据库进行交互,具体实现BLOB数据的存储和读取操作,包括创建存储过程和Ruby脚本示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


转载于:https://my.oschina.net/dking/blog/666308

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值