8

How can I execute a SQL query from a Rails application to a MySQL database?

My application uses Postgres as a primary database, but I need to read some information from a secondary MySQL database. I can't create models because the MySQL database has more than 100 tables, named in an incompatible way for every table. Can it be done without ActiveRecord or some other way?

1
  • Rails does support forcing table names for a particular model using set_table_name "foo". If the number of tables is static and it's likely that you'll use them all, I would start creating models in the order they're needed. There is also support in AR:Base for specifying the primary key field. Commented Jan 17, 2012 at 13:50

1 Answer 1

13

You can use mysql2 gem directly. Read the documentation here: https://github.com/brianmario/mysql2

Or:

You can create a new class like MysqlConnection like this:

class MysqlConnection < ActiveRecord::Base
  self.establish_connection(:adapter => 'mysql', :database => 'some-database-name') # Set all the other required params like host, user-name, etc
end

From now on, you can do,

MysqlConnection.connection.select_all("SELECT * FROM table_name")

Follow the link to understand how to store the configuration details in database.yml: http://weare.buildingsky.net/2006/12/06/multiple-concurrent-database-connections-with-activerecord

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

1 Comment

Thank you for you answer! It's the best solution for me.

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.