我如何从没有模型的Rails应用程序查询MySQL数据库? [英] How can I query a MySQL database from a Rails app without models?

查看:48
本文介绍了我如何从没有模型的Rails应用程序查询MySQL数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何执行从Rails应用程序到MySQL数据库的SQL查询?

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

我的应用程序使用Postgres作为主数据库,但是我需要从辅助MySQL数据库读取一些信息.我无法创建模型,因为MySQL数据库有100多个表,每个表都以不兼容的方式命名.可以在没有ActiveRecord或其他方式的情况下完成吗?

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?

推荐答案

您可以直接使用mysql2 gem.在此处阅读文档: https://github.com/brianmario/mysql2

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

或者:

您可以像这样创建一个新类,例如MysqlConnection:

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

从现在开始,您可以做

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

点击链接以了解如何将配置详细信息存储在database.yml中:

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

这篇关于我如何从没有模型的Rails应用程序查询MySQL数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆