电脑技术学习

如何使用Ruby脚本调用Oracle存储过程

dn001
使用Ruby脚本调用Oracle存储过程的示例:

1.首先创建Oracle存储过程test:

SQL> CREATE OR REPLACE PROCEDURE test(p1 in varchar2,p2 out varchar2  ) is
2  BEGIN
3    select p1||' PROCEDURE EXECUTED!' into p2 from dual ;
4  end;
5  /
Procedure created

2.再写Ruby脚本,调用存储过程test,脚本内容如下,将脚本保存为:Call_proc_test.rb:

require 'dbi'

db_read_str = 'BEGIN test(?, ?); END;'
dbh = DBI.connect('DBI:OCI8:TNSDBNAME', 'username', 'password')
sth_db = dbh.prepare(db_read_str)
sth_db.bind_param(1, 'test:',''*50)  # allow for up to 50 chars
sth_db.bind_param(2, ' ' * 100)      # allow for up to 100 chars
sth_db.execute
str = sth_db.func(:bind_value, 2)
puts str
dbh.disconnect

3.检查Ruby语法错误:

C:>ruby -cw Call_proc_test.rb
Syntax OK

C:>

4.最后执行Ruby脚本:

C:>ruby  Call_proc_test.rb
test: PROCEDURE EXECUTED!

C:>

注释:如果是Windows环境下,大家也可以通过双击Call_proc_test.rb 文件来运行Ruby脚本。