简体   繁体   English

在Ruby on Rails中动态连接到第二个MySQL数据库

[英]Dynamic connection to second MySQL database in Ruby on Rails

I'm working on a rails application that will migrate user content. 我正在开发将迁移用户内容的Rails应用程序。 I need to take in database parameters via a form and use them to connect to the given database. 我需要通过表单获取数据库参数,并使用它们连接到给定的数据库。 What's the best way to achieve this? 实现此目标的最佳方法是什么? I've attempted using Mysql.real_connect with no joy. 我尝试不Mysql.real_connect使用Mysql.real_connect

您可以拨打establish_connection用新的参数,然后用connection正常。

I had a similar need in a rake task. 我在耙任务中也有类似的需求。 I ended up using basically the following code after the rails environment had been loaded by rake. 在rake加载了rails环境之后,我基本上使用了以下代码。

require "mysql2"

#Constants
#---------
DB_HOST = "example.com"
DB_USER = "username"
DB_PASSWORD = "password"
DB = "db_name"

SQL = "SELECT * FROM BLAH;"

client = Mysql2::Client.new(:host => DB_HOST, :username => DB_USER,
                            :password=> DB_PASSWORD, :database => DB)

rs = client.query(SQL)
rs.each do |h|
  #Work on Row here
end

It is using mysql (mainly because I got tired of mysql crashing the script), but the process should be the same. 它正在使用mysql(主要是因为我对mysql使脚本崩溃感到厌倦),但是过程应该是相同的。

Check ruby/mysql 检查ruby / mysql

require "mysql"
my = Mysql::new("host", "user", "passwd", "db")
res = my.query("select * from tbl")
res.each do |row|
  col1 = row[0]
  col2 = row[1]
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM