如何在非Rails应用程序中使用ActiveRecord创建新的MySQL数据库? [英] How to create a new MySQL database with ActiveRecord in a non-rails app?

查看:77
本文介绍了如何在非Rails应用程序中使用ActiveRecord创建新的MySQL数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个使用ActiveRecord的无轨纯红宝石应用程序。我想编写一个rake文件,为它创建数据库和表。我尝试以下代码

I'm building a non-rails pure ruby app that uses ActiveRecord. I want to write a rake file that creates a database and tables for it. I try the following code

namespace :db do
  task :create do
    conn = ActiveRecord::Base.connection
    create_db = "CREATE DATABASE foo_dev"
    conn.execute(create_db)
  end
end

但这给了我

ActiveRecord::ConnectionNotEstablished: ActiveRecord::ConnectionNotEstablished

错误。好吧,这很明显,因为我没有将ActiveRecord连接到任何数据库。

error. Well, this is obvious because I didn't connect ActiveRecord to any database.

我该怎么办?

编辑:我想创建一个MySQL数据库。

I want to create a MySQL database.

推荐答案

感谢答案但是,正如我在问题中所做的编辑一样,我忘了提到我要创建一个MySQL数据库。我无法通过ActiveRecord创建MySQL数据库。然后,借助 mysql2 gem解决了该问题。这是我的解决方案:

Thanks for answers but as I've edited in my question, I forgot to mention that I want to create a MySQL DB. I've failed to create a MySQL db via ActiveRecord. Then I've solved the problem with the help of mysql2 gem. Here's my solution:

client = Mysql2::Client.new(:host => 'localhost', :username=>"#{YOUR_MYSQL_USERNAME}", :password=> "#{YOUR_MYSQL_PASSWORD}")
client.query("CREATE DATABASE company_db")
client.query('USE company_db')
client.query('CREATE TABLE employees ...')
...

这里的 USE company_db查询很重要,因为它告诉gem我们要对该数据库运行查询。

Here 'USE company_db' query is important because, it tells to the gem that we want to run queries on this database.

这篇关于如何在非Rails应用程序中使用ActiveRecord创建新的MySQL数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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