約15万行のタブ区切りのテキストファイルをSQLiteにインポートするRubyスクリプトを作成しています。ここまでです:
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'
一重引用符がエスケープされているように見えますが、それでもエラーが発生するのはなぜですか?