教你快速實(shí)現(xiàn)Ruby操作Oracle數(shù)據(jù)庫(kù)
對(duì)于一個(gè)編程人員來說,熟練的掌握編程語言操作數(shù)據(jù)庫(kù)是一個(gè)必要的技能之一。下面我們就為大家介紹有關(guān)Ruby操作Oracle數(shù)據(jù)庫(kù)的實(shí)現(xiàn)方法。#t#
Ruby操作Oracle數(shù)據(jù)庫(kù)1.在如下地址下載Ruby:
http://www.ruby-lang.org/zh_CN/downloads/
在這里我們下載Ruby的windows版本:
點(diǎn)擊:Ruby 1.8.6 一步安裝 連接,下載文件:ruby186-26.exe
Ruby操作Oracle數(shù)據(jù)庫(kù)2.安裝Ruby
雙擊ruby186-26.exe運(yùn)行即可安裝Ruby。
Ruby操作Oracle數(shù)據(jù)庫(kù)3.下載安裝Ruby/OCI8
為了使 Ruby 能夠與我們的 Oracle 數(shù)據(jù)庫(kù)通信,需要使用 Ruby/OCI8??蓮?
http://rubyforge.org/projects/ruby-oci8/ 下載文件:
ruby-oci8-1.0.0-mswin32.rb
雙擊該文件即可完成Ruby/OCI8的安裝
Ruby操作Oracle數(shù)據(jù)庫(kù)4.書寫Ruby腳本文件,完成從文本文件offeridlist.txt中讀取商品ID并更改商品狀態(tài)的任務(wù):
新建一個(gè)文本文件,輸入如下代碼,保存為: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 \"請(qǐng)輸入商品原來狀態(tài):\"
old_state=gets
old_state=old_state.chomp; #chomp去除輸入行后面的換行
print \"請(qǐng)輸入商品目標(biāo)狀態(tài):\"
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+\"個(gè)商品狀態(tài)已經(jīng)由\"+old_state.to_s+\"改為:\"
puts str_state
end
dbh.commit
dbh.disconnect
puts \"\"
print \"請(qǐng)按任意鍵退出:\"
gets
exit
新建文本文件:offeridlist.txt,在該文件中保存商品ID:
120010020
120010022
將文件offeridlist.txt、update_offer_state.rb保存在同一個(gè)目錄下
Ruby操作Oracle數(shù)據(jù)庫(kù)5.檢查Ruby腳本的語法錯(cuò)誤
在命令行輸入 ruby -cw update_offer_state.rb 完成腳本update_offer_state.rb的語法檢查
如果檢查語法沒有錯(cuò)誤,顯示如下: [Page]
C:\\>ruby -cw update_offer_state.rb
Syntax OK
Ruby操作Oracle數(shù)據(jù)庫(kù)6.運(yùn)行Ruby腳本:
(1).在命令行輸入 ruby update_offer_state.rb 即開始運(yùn)行 update_offer_state.rb腳本 。
(2).windows環(huán)境下,雙擊文件update_offer_state.rb也可以 開始運(yùn)行該腳本。