I'm working on a rails application that will migrate user content. 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.
3 Answers
You can call establish_connection with your new parameters and then use connection normally.
1 Comment
tom eustace
Thanks, this is what I ended up using.
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.
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.
1 Comment
Joel Grannas
did you set client in an initializer file, and then just use client.query() from your controllers? I need to do something similar to this, but I am having trouble deciding where the "connection" should be placed so It can be reused. and I'm worried about having too many connections, and connections not closing... can you post example/gist?
Check 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