1

I want to connect to a MySQL database without adding it to database.yml. How can I connect and run a query on that database?

I understand I need to do something like this, but what's the code for actually making the connection to the specific IP/port first?

query = "SELECT 1"
ActiveRecord::Base.connection.execute(query)
2
  • Just using ActiveRecord or through the mysql2 gem? Commented Jun 5, 2017 at 16:09
  • @SebastiánPalma either works Commented Jun 5, 2017 at 17:16

1 Answer 1

4

You might want to try ActiveRecord::Base.establish_connection

Example from documentation:

ActiveRecord::Base.establish_connection(
  :adapter  => "mysql",
  :host     => "localhost",
  :username => "myuser",
  :password => "mypass",
  :database => "somedatabase"
)

From:

https://apidock.com/rails/ActiveRecord/Base/establish_connection/class

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

2 Comments

set conn = to that. Then conn.execute(query) ?
My guess is that you need to use the code above first on its own, and then you can use ActiveRecord::Base.connection as you did in the question. Does that work?

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.