如何将 SQL 文件导入 Rails 数据库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8342642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:29:41  来源:igfitidea点击:

How can I import a SQL file into a Rails database?

sqlruby-on-rails

提问by Nathan Long

I've got a .sqlfile that I'd like to load into my Rails database using a Rake task. How can I do this?

我有一个.sql文件,我想使用 Rake 任务将其加载到我的 Rails 数据库中。我怎样才能做到这一点?

采纳答案by Abel

The easiest way:

最简单的方法:

bundle exec rails db < $SQL_FILE

example:

例子:

bundle exec rails db < my_db.sql

回答by Nathan Long

The Easy Way

简单的方法

This works for simple cases.

这适用于简单的情况。

ActiveRecord::Base.connection.execute(IO.read("path/to/file"))

Solution found on the Ruby On Rails mailing listfrom 2006 (but still works in 2011 on Rails 3.1).

2006年在Ruby On Rails 邮件列表中找到的解决方案(但在 2011 年仍然适用于 Rails 3.1)。

Footnotes

脚注

  • This related questionimplied this solution, but rejected it for big imports. I wanted to show it explicitly, since it works for smaller ones.
  • The file I was trying to import contained a LOCK TABLESfollowed by an insert. The data was for a MySQL database. Mysql2said it had an invalid SQL syntax error until I removed the lock and unlock statements.
  • 这个相关的问题暗示了这个解决方案,但拒绝了大进口。我想明确地展示它,因为它适用于较小的。
  • 我试图导入的文件包含一个LOCK TABLES后跟一个插入。数据用于 MySQL 数据库。Mysql2说它有一个无效的 SQL 语法错误,直到我删除了锁定和解锁语句。

回答by joost

On MySQL this gave me a syntax error. Splitting the sql into statements made it work.

在 MySQL 上,这给了我一个语法错误。将 sql 拆分为语句使其工作。

sql = File.read(sql_file)
statements = sql.split(/;$/)
statements.pop # remove empty line
ActiveRecord::Base.transaction do
  statements.each do |statement|
    connection.execute(statement)
  end
end