教你快速實現Ruby操作Oracle數據庫
對于一個編程人員來說,熟練的掌握編程語言操作數據庫是一個必要的技能之一。下面我們就為大家介紹有關Ruby操作Oracle數據庫的實現方法。#t#
Ruby操作Oracle數據庫1.在如下地址下載Ruby:
http://www.ruby-lang.org/zh_CN/downloads/
在這里我們下載Ruby的windows版本:
點擊:Ruby 1.8.6 一步安裝 連接,下載文件:ruby186-26.exe
Ruby操作Oracle數據庫2.安裝Ruby
雙擊ruby186-26.exe運行即可安裝Ruby。
Ruby操作Oracle數據庫3.下載安裝Ruby/OCI8
為了使 Ruby 能夠與我們的 Oracle 數據庫通信,需要使用 Ruby/OCI8。可從
http://rubyforge.org/projects/ruby-oci8/ 下載文件:
ruby-oci8-1.0.0-mswin32.rb
雙擊該文件即可完成Ruby/OCI8的安裝
Ruby操作Oracle數據庫4.書寫Ruby腳本文件,完成從文本文件offeridlist.txt中讀取商品ID并更改商品狀態的任務:
新建一個文本文件,輸入如下代碼,保存為:update_offer_state.rb
require ’dbi’
i=0
dbh = DBI.connect(’DBI:OCI8:TNSDBNAME’, ’username’, ’password’)
sqlCapitalsUpdate = \"UPDATE product_offer SET state = ? WHERE offer_id in(?) and state=?\"
print \"請輸入商品原來狀態:\"
old_state=gets
old_state=old_state.chomp; #chomp去除輸入行后面的換行
print \"請輸入商品目標狀態:\"
str_state=gets
str_state=str_state.chomp; #chomp去除輸入行后面的換行
puts \"\"
file1 = File.open(’offeridlist.txt’,\"r\")
#str=file.readlines
#puts str
file1.each do |l|
rs = dbh.prepare(’SELECT state FROM product_offer where offer_id=’+l.to_s)
rs.execute
rsRow = rs.fetch
if rsRow.to_s==old_state.to_s then
puts l
i=i+1
dbh.do(sqlCapitalsUpdate,str_state.to_s,l.to_i,old_state.to_s)
end
end
file1.close
if i.to_i!=0 then
puts \"\"
print \"以上\"+i.to_s+\"個商品狀態已經由\"+old_state.to_s+\"改為:\"
puts str_state
end
dbh.commit
dbh.disconnect
puts \"\"
print \"請按任意鍵退出:\"
gets
exit
新建文本文件:offeridlist.txt,在該文件中保存商品ID:
120010020
120010022
將文件offeridlist.txt、update_offer_state.rb保存在同一個目錄下
Ruby操作Oracle數據庫5.檢查Ruby腳本的語法錯誤
在命令行輸入 ruby -cw update_offer_state.rb 完成腳本update_offer_state.rb的語法檢查
如果檢查語法沒有錯誤,顯示如下: [Page]
C:\\>ruby -cw update_offer_state.rb
Syntax OK
Ruby操作Oracle數據庫6.運行Ruby腳本:
(1).在命令行輸入 ruby update_offer_state.rb 即開始運行 update_offer_state.rb腳本 。
(2).windows環境下,雙擊文件update_offer_state.rb也可以 開始運行該腳本。