天天看點

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}")

  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

  #使用sql語句

  dbh.do("set autocommit=0")

  dbh.do("begin")

  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

    sth.finish

  rescue

  #上面這段查詢可以改寫為:

  #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

  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