天天看点

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