ruby的数据库操作

目前Ruby访问数据库的方法可分为4层,如下图所示:
------------------------------------------------------
| 4 - ActiveRecord ORM
------------------------------------------------------
| 3 - DBI抽象层
------------------------------------------------------
| 2 - 对应数据库的Ruby驱动层(Ruby-Pr...)
------------------------------------------------------
| 1 - 数据库层(MySQL/Postgresql...)
------------------------------------------------------
最底层是数据库层,这层对应了各种不同的关系型数据库,比如MySQL/Oracle等。它上面的是驱动层,就是各数据库对应的Ruby驱动插件,这层的插件是数据库相关的,就是不同的数据库驱动插件也不同。然后在驱动层的基础上,我们就可以发展出DBI层(Database Interface)。在DBI这层,我们就可以编写独立于数据库的代码了。哈,这就是抽象的力量,也是我们软件开发者一直在追求的。不过当前的一个流行趋势是ORM,就是对象/关系型数据库表的映射,ActiveRecord就是一个 Ruby 的ORM组件,我们在下面可以看到它的一些应用
 
示例一:
require 'postgres'

# 对应参数:主机名,端口号,连接参数,指定pgtty,数据库,用户名,密码
conn = PGconn.connect('localhost', 5432, '', '', 'testdb', 'postgres', 'postgres')
#    exec方法直接执行SQL语句,返回一个PGresult对象
conn.exec("insert into mytab(msg) values('I was inserted by driver.')")

# 取得表格数据,并分行打印
res = conn.exec('select * from mytab').result
for data in res
    p data
end

conn.close    # 关闭数据库连接
 
示例二(Ruby DBI):
要使用Ruby DBI,我们必须下载安装它,这个是Ruby DBI的官方站点:
http://rubyforge.org/projects/ruby-dbi
配置:
    ruby setup.rb config --with=dbi,dbd_pg
注:这个--with参数根据您的数据库类型选择(可以多个),这里仅选postgresql。
    ruby setup.rb setup
最后安装:sudo ruby setup.rb install
 
require 'dbi'

# 根据不同的数据库,填不同的连接字符串,然后跟用户名、密码
dbh = DBI.connect('DBI:Pg:testdb', 'postgres', 'postgres')

# 可以使用sql替换,避免注入式攻击。
sql = 'insert into mytab(msg) values(?)'
dbh.do(sql, 'I was inserted by ruby-dbi.')

# dbi有完善的事务支持
sth = dbh.prepare('select * from mytab')
sth.execute
while row = sth.fetch
    p row
end
sth.finish

dbh.disconnect # 关闭数据库连接
 
示例三(ActiveRecord):
ActiveRecord是 rails 的一个组件,安装gem install activerecord
 
require 'rubygems'
require_gem 'activerecord'    # 请注意使用rubygems时候的声明方式

# 连接数据库,按需求填写各种参数。
ActiveRecord::Base.establish_connection(:adapter => "postgresql",
    :host => "localhost", :database => "testdb")
class Mytab < ActiveRecord::Base # 开始ORM对应
    set_table_name 'mytab' # 指定数据库名
end

# 插入一条数据
tab = Mytab.new
tab.msg = 'I was inserted by ActiveRecord.'
tab.save

# 显示所有数据
data = Mytab.find(:all)
data.each { |line| puts "['#{line[:id]}', '#{line[:msg]}']" }

你可能感兴趣的:(ruby相关)