我正在创建一个 Ruby 脚本,以将大约 150k 行的制表符分隔文本文件导入 SQLite。到目前为止:
require 'sqlite3'
file = File.new("/Users/michael/catalog.txt")
string = []
# Escape single quotes, remove newline, split on tabs,
# wrap each item in quotes, and join with commas
def prepare_for_insert(s)
s.gsub(/'/,"\\\\'").chomp.split(/\t/).map {|str| "'#{str}'"}.join(", ")
end
file.each_line do |line|
string << prepare_for_insert(line)
end
database = SQLite3::Database.new("/Users/michael/catalog.db")
# Insert each string into the database
string.each do |str|
database.execute( "INSERT INTO CATALOG VALUES (#{str})")
end
尽管在我的方法gsub
中转义单引号,但脚本在包含单引号的第一行出错:prepare_for_insert
/Users/michael/.rvm/gems/ruby-1.9.3-p0/gems/sqlite3-1.3.5/lib/sqlite3/database.rb:91:
in `initialize': near "s": syntax error (SQLite3::SQLException)
它在第 15 行出错。如果我用 来检查该行puts string[14]
,我可以看到它在“s”附近显示错误的位置。它看起来像这样:'Touch the Top of the World: A Blind Man\'s Journey to Climb Farther Than the Eye Can See'
看起来单引号被转义了,为什么我仍然收到错误?