0

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 3

3

You can call establish_connection with your new parameters and then use connection normally.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is what I ended up using.
1

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

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?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.