ruby DBI安裝使用指南
1.安裝首先,我是使用mysql進行測試的,你的機器上需要安裝mysql數據庫。
然後執行:
gem install mysql
到rubyforge下載ruby-DBI,解壓後cd到目錄運行如下命令:
ruby setup.rb config --with=dbi,dbd_mysql
ruby setup.rb setup
ruby setup.rb install
完整的setup命令參數參考DBI的doc
2.完整例子
DBI是一類似於ODBC的開發式的統一的數據庫編程接口,結構層次上可以分為兩層:
1.Database Interface——數據庫接口層,與數據庫無關,提供與數據庫無關的標準接口
2.Database Driver——數據庫驅動,與數據庫相關
DBI也是很簡單易用的,一個完整的使用例子,對於初學者可能有點幫助:
require 'dbi'
begin
#連接數據庫
dbh=DBI.connect("DBI:Mysql:dbi_test:localhost","root","")
dbh.columns("simple").each do |h|
p h
end
#示範3種事務處理方式
#手動commit
dbh["AutoCommit"]=false
1.upto(10) do |i|
sql = "insert into simple (name, author) VALUES (?, ?)"
dbh.do(sql, "Song #{i}", "#{i}")
end
dbh.commit
#使用transaction方法
dbh.transaction do |dbh|
1.upto(10) do |i|
sql = "insert into simple (name, author) VALUES (?, ?)"
dbh.do(sql, "Song #{i}", "#{i}")
end
end
#使用SQL語句
dbh.do("SET AUTOCOMMIT=0")
dbh.do("BEGIN")
dbh["AutoCommit"]=false
dbh.do("UPDATE simple set name='test' where id='1'")
dbh.do("COMMIT")
#查詢
sth=dbh.execute("select count(id) from simple")
puts "bookCount:#{sth.fetch[0]}"
sth.finish
begin
sth=dbh.prepare("select * from simple")
sth.execute
while row=sth.fetch do
p row
end
sth.finish
rescue
end
#上麵這段查詢可以改寫為:
#dbh.select_all("select * from simple") do |row|
# p row
#end
#使用工具類輸出xml格式結果集以及測量查詢時間
sql="select * from simple"
mesuretime=DBI::Utils::measure do
sth=dbh.execute(sql)
end
puts "SQL:#{sql}"
puts "Time:#{mesuretime}"
rows=sth.fetch_all
col_names=sth.column_names
sth.finish
puts DBI::Utils::XMLFormatter.table(rows)
dbh.do("delete from simple")
rescue DBI::DatabaseError=>e
puts "error code:#{e.err}"
puts "Error message:#{e.errstr}"
ensure
dbh.disconnect if dbh
end
begin
#連接數據庫
dbh=DBI.connect("DBI:Mysql:dbi_test:localhost","root","")
dbh.columns("simple").each do |h|
p h
end
#示範3種事務處理方式
#手動commit
dbh["AutoCommit"]=false
1.upto(10) do |i|
sql = "insert into simple (name, author) VALUES (?, ?)"
dbh.do(sql, "Song #{i}", "#{i}")
end
dbh.commit
#使用transaction方法
dbh.transaction do |dbh|
1.upto(10) do |i|
sql = "insert into simple (name, author) VALUES (?, ?)"
dbh.do(sql, "Song #{i}", "#{i}")
end
end
#使用SQL語句
dbh.do("SET AUTOCOMMIT=0")
dbh.do("BEGIN")
dbh["AutoCommit"]=false
dbh.do("UPDATE simple set name='test' where id='1'")
dbh.do("COMMIT")
#查詢
sth=dbh.execute("select count(id) from simple")
puts "bookCount:#{sth.fetch[0]}"
sth.finish
begin
sth=dbh.prepare("select * from simple")
sth.execute
while row=sth.fetch do
p row
end
sth.finish
rescue
end
#上麵這段查詢可以改寫為:
#dbh.select_all("select * from simple") do |row|
# p row
#end
#使用工具類輸出xml格式結果集以及測量查詢時間
sql="select * from simple"
mesuretime=DBI::Utils::measure do
sth=dbh.execute(sql)
end
puts "SQL:#{sql}"
puts "Time:#{mesuretime}"
rows=sth.fetch_all
col_names=sth.column_names
sth.finish
puts DBI::Utils::XMLFormatter.table(rows)
dbh.do("delete from simple")
rescue DBI::DatabaseError=>e
puts "error code:#{e.err}"
puts "Error message:#{e.errstr}"
ensure
dbh.disconnect if dbh
end
文章轉自莊周夢蝶 ,原文發布時間5.17
最後更新:2017-05-17 13:35:12