I am creating a Ruby script to import a text file with tab delimiters about 150 thousand lines long in SQLite. Here it is still:
require 'sqlite3'
file = File.new("/Users/michael/catalog.txt")
string = []
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")
string.each do |str|
database.execute( "INSERT INTO CATALOG VALUES (#{str})")
end
The script error in the first line containing a single quote, despite gsubto avoid single quotes in my method 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)
This is an error on line 15. If I check this line with puts string[14], I see where it shows the error near "s". It looks like this:'Touch the Top of the World: A Blind Man\ Journey to Climb Farther Than the Eye Can See'
It seems that the single quote is escaped, so why am I still getting the error?
source
share