近期的一个项目中需要用到Rails访问Oracle,项目本身连接的是mysql
?
1、在Gemfil中增加所需的gem
gem ruby-oci8 #ruby使用Oracle提供的OCI8接口连接Oracle的接口 bundle install
2、创建连接
connection=OCI8.new("ceshi","ceshi","127.0.0.1:1521/ceshi") #参数分别为用户名、密码和实例
3、查询
查询单条记录
1.9.2p320 :005 > connection.select_one("select lsh,line from web_output_data where rownum=1") => ["923536", "2011.05\u00012393.00\u00012011.03.21\u0001478.60"] #返回结果是个数组
?查询返回多条记录
def select_all(sql,*bindvars) connection =self.connection rs = Array.new connection.exec(sql,*bindvars) do |row| rs << row end connection.logoff rs end
?4、插入、更新、删除
def update(sql,*bindvars) conn = self.connection rs=conn.exec(sql,*bindvars) conn.commit conn.logoff rs end //OracleAccess.new.update("update user set name=:1,age=:2",'litbadboy',25)
?5、存储过程的调用
def list(dwm) conn = self.connection proc = "begin proc_name(:1,:2,:3);end;" cursor=conn.parse(proc) cursor.bind_param(':1',dwm,String) #输入参数 cursor.bind_param(':2',nil,String) #输出参数 cursor.bind_param(':3',nil,String) #输出参数 cursor.exec() lsh=cursor[':2'] msg=cursor[':3'] cursor.close conn.logoff [lsh,msg] end
?6、函数调用
def self.lsh proc="begin :1 := wsbs_interface.getlsh;end;" cursor =access.parse(proc) cursor.bind_param(':1',nil,String) cursor.exec() seq=cursor[':1'] cursor.close seq end
?