【问题标题】:Executing raw sql against multiple data bases对多个数据库执行原始 sql
【发布时间】:2017-03-22 14:13:04
【问题描述】:

这是对 executing raw sql。我正在做一个项目,我需要从多个数据库中传输信息。我将如何做类似于

的事情
sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)

但支持选择连接??

【问题讨论】:

    标签: ruby-on-rails sql-server sqlite activerecord


    【解决方案1】:

    您可以使用ActiveRecord::Base.establish_connection 切换数据库连接。代码应该是这样的:

    #database.yml
    development:
      adapter: postgresql
      host: 127.0.0.1
      username: postgres
      password: postgres
      database: development_db
    
    development_another_db:
      adapter: postgresql
      host: 127.0.0.1
      username: postgres
      password: postgres
      database: another_db
    
    
    ActiveRecord::Base.establish_connection :development_another_db
    sql = "Select * from ... your sql query here"
    records_array = ActiveRecord::Base.connection.execute(sql)
    
    ActiveRecord::Base.establish_connection :development
    sql = "Another select"
    records_array = ActiveRecord::Base.connection.execute(sql)
    

    您可以在Rails documentation 中找到有关establish_connection 的详细信息。

    【讨论】:

    • 这可以跨连接完成以从一个数据库中选择并插入另一个数据库吗?
    • @SawyerMerchant,是的,当然。由于sql 这里只是一个纯字符串,与数据库连接或活动记录没有任何关系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多