1

我正在尝试编写一个 SQL INSERT 语句(故意不使用 ActiveRecord),最终一次性插入大量行。

inserts.push "('#{x}', #{p}, '#{day.strftime("%Y-%m-%d")}', #{student.id}, '#{created_at}', '#{created_at}', '#{session}')"

sql = "INSERT INTO attendance_marks (mark_code, present, date_recorded, student_id, created_at, updated_at, sess) VALUES #{inserts.join(", ")}"
conn =  ActiveRecord::Base.connection
conn.execute sql

但我得到一个错误,因为值为xis "\"。如何解决这个问题并成功地将反斜杠字符插入 MySQL DB?

感觉它应该很简单,而且可能很简单,但我已经竭尽全力试图解决它。

错误信息:

>> Attendance.parse_attendance_string Student.find(1), "\\", DateTime.new(2012,9,1)
Student Load (0.7ms)  SELECT `students`.* FROM `students` WHERE `students`.`id` = 1 LIMIT 1
(0.4ms)  INSERT INTO attendance_marks (mark_code, present, date_recorded, student_id, created_at, updated_at, sess) VALUES ('\', 1, '2012-09-01', 1, '2012-08-03 15:58:19', '2012-08-03 15:58:19', 'AM')
ActiveRecord::StatementInvalid: Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2012-09-01', 1, '2012-08-03 15:58:19', '2012-08-03 15:58:19', 'AM')' at line 1: INSERT INTO attendance_marks (mark_code, present, date_recorded, student_id, created_at, updated_at, sess) VALUES ('\', 1, '2012-09-01', 1, '2012-08-03 15:58:19', '2012-08-03 15:58:19', 'AM')
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:233:in `query'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:233:in `execute'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_adapter.rb:280:in `log'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.2.0/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_adapter.rb:275:in `log'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:233:in `execute'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/mysql2_adapter.rb:214:in `execute'
from /Users/mike.campbell/projects/cpoms_messy/app/models/attendance.rb:76:in `parse_attendance_string'
from (irb):115
>>
4

1 回答 1

1

我建议您查看ActiveRecord import,而不是自己清理输入、处理反斜杠并加入查询。它提供了一个 Gem,可让您使用以下语法在语义上创建批量插入:

books = []
10.times do |i| 
  books << Book.new(:name => "book #{i}")
end
Book.import books
于 2012-08-03T15:05:46.977 回答