查询不同于标准app db的mysql db

yhived7q  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(341)

我将Rails2.2.2和Ruby1.8.6与mysql一起使用(请不要告诉我我需要升级ruby/rails)。
我在本地mysql中安装了实时数据库的备份,作为不同的数据库。这有时对于查询历史数据很有用,因为它并不总是保存在活动数据库中。
我想做的是这样的事情

school_ids = [123, 456, 789]
signin_counts = {}

# collect current data

school_ids.each do |school_id|
  signin_counts[school_id] ||= {}
  signin_counts[school_id][:now] = ActiveRecord::Base.connection.select_value("select count(*) from sign_ins where school_id = #{school.id}").to_i
end

# switch to the old database - how to do this?

CURRENT_DB = "my_old_backup_db_name"
school_ids.each do |school_id|
  signin_counts[school_id] ||= {}
  signin_counts[school_id][:then] = ActiveRecord::Base.connection.select_value("select count(*) from sign_ins where school_id = #{school.id}").to_i
end

# switch back

CURRENT_DB = "my_regular_db_name"

有人知道怎么做吗 CURRENT_DB = 部分?谢谢

mznpcxlj

mznpcxlj1#

感谢@davegoldberg的评论,我提出了这两种方法来说明如何做到这一点。显然有更干净的 Package 方法,我只想展示一个简单的方法。

def use_old_db
  config = {
    :adapter => 'mysql',
    :host => 'localhost',
    :username => 'my_username',
    :password => 'my_password',
    :database => 'name_of_database'
  }
  ActiveRecord::Base.establish_connection(config)
end

def use_new_db
  ActiveRecord::Base.establish_connection(RAILS_ENV.to_sym)
end
bvpmtnay

bvpmtnay2#

如果在继承的模型文件中 ActiveRecord::Base 你可以做:

mysql_database = establish_connection (
    adapter: "mysql",
    host: "your_db_host",
    username: "your_db_username",
    password: "your_db_password",
    database: "your_db_name"
  )

这篇文章很好地解释了如何使用 establish_connection http://ilikestuffblog.com/2012/09/21/establishing-a-connection-to-a-non-default-database-in-rails-3-2-2/ 而且可能已经足够老了,可以与您的rails版本相关联,不过,在版本2和版本3之间有很多变化

相关问题