MySQL INSERT语句中的反斜杠 - Ruby on Rails

时间:2012-08-03 15:00:58

标签: mysql ruby-on-rails

我正在尝试编写一个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

但我收到错误,因为x的值为"\"。如何绕过这个并成功将反斜杠字符插入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
>>

1 个答案:

答案 0 :(得分:1)

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

books = []
10.times do |i| 
  books << Book.new(:name => "book #{i}")
end
Book.import books