使用 ActiveRecord 从文件中执行 SQL-语句
Execute SQL-Statement from File with ActiveRecord
我有一个自动生成的 *.sql 文件,其中包含我的数据库的所有删除和创建信息。
现在我想用 ActiveRecord 执行 SQL 语句:
ActiveRecord::Base.connection.execute File.read( filename )
我得到的错误是
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'DROP TABLE IF EXISTS `airports`;
后面是*.sql文件的完整内容。
但是,如果我只是将 *.sql 的内容复制并粘贴到 PhpMyAdmin 中并在那里执行,它就可以毫无问题地运行。
有更好的方法吗?我必须在某处指定 mysql-version 吗?
Afaik ActiveRecord::Base.connection.execute
进行了一些清理,不允许 运行 一次进行多个查询。
一种解决方法可能是将文件的内容拆分为单个查询并运行它们独立:
queries = File.read(filename).split(';')
queries.each { |query| ActiveRecord::Base.connection.execute(query) }
更高级的版本将跳过空条件。可能会出现空字符串,因为 split
returns 最后一个 ';' 之后的空字符串。我会跳过这样的字符串:
queries = File.read(filename).split(';')
queries.each do |query|
query.strip!
ActiveRecord::Base.connection.execute(query) unless query.empty?
end
我有一个自动生成的 *.sql 文件,其中包含我的数据库的所有删除和创建信息。
现在我想用 ActiveRecord 执行 SQL 语句:
ActiveRecord::Base.connection.execute File.read( filename )
我得到的错误是
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'DROP TABLE IF EXISTS `airports`;
后面是*.sql文件的完整内容。
但是,如果我只是将 *.sql 的内容复制并粘贴到 PhpMyAdmin 中并在那里执行,它就可以毫无问题地运行。
有更好的方法吗?我必须在某处指定 mysql-version 吗?
Afaik ActiveRecord::Base.connection.execute
进行了一些清理,不允许 运行 一次进行多个查询。
一种解决方法可能是将文件的内容拆分为单个查询并运行它们独立:
queries = File.read(filename).split(';')
queries.each { |query| ActiveRecord::Base.connection.execute(query) }
更高级的版本将跳过空条件。可能会出现空字符串,因为 split
returns 最后一个 ';' 之后的空字符串。我会跳过这样的字符串:
queries = File.read(filename).split(';')
queries.each do |query|
query.strip!
ActiveRecord::Base.connection.execute(query) unless query.empty?
end