共享数据库句柄

时间:2012-03-03 19:52:28

标签: ruby database-connection dbi sharing

我需要在一些Ruby脚本中共享数据库句柄。我正在使用DBI gem连接到数据库。请考虑以下示例

#a.rb
class A
  require 'dbi'

  def connect
    if a database handle is already open return it
    else create a new one and return it
  end
end

#b.rb
class B
  require 'a'
  a = A.new
  dbh = a.connect
  #some database queries here
end

#c.rb
class C
  require 'a'
  a = A.new
  dbh = a.connect #Here the database handle created by class B should be returned 
end

我理解类实例变量是实现上述目标的方法。有人可以提供一些见解吗?

DBI是否有类似于Log4r的内容

class A
  require 'log4r'
  Log4r::Logger.new('SO') #create a new instance here
end

class B
  require 'a'
  Log4r::Logger['SO'] # get the existing instance here
end

非常感谢。

1 个答案:

答案 0 :(得分:2)

以下使用Singleton来管理DBI句柄的哈希值。第一次使用这些选项请求连接时,它将为给定的一组连接选项(args将传递给DBI.connect)创建一个新句柄。具有相同选项的后续请求将获得已打开的句柄。

# there_can_be_only_one_dbh.rb

require 'dbi'
require 'singleton'

class ThereCanBeOnlyOneDBH
  include Singleton

  DEFAULT_CONNECT_OPTIONS = ['dsn','user','pw']

  def connect( *options )
    options = DEFAULT_CONNECT_OPTIONS unless options and !options.empty?
    @handles ||= {}
    @handles[options.join('|')] ||= DBI.connect( *options )
  end
end

# b.rb
require 'there_can_be_only_one_dbh'

class B
  def initialize( *dbi_connect_options )
    @dbh = ThereCanBeOnlyOneDBH.instance.connect( *dbi_connect_options )
  end

  # methods which issue queries using @dbh
end

# c.rb
require 'there_can_be_only_one_dbh'

class C
  def initialize( *dbi_connect_options )
    @dbh = ThereCanBeOnlyOneDBH.instance.connect( *dbi_connect_options )
  end

  # other methods which issue queries using @dbh
end