Row exception for Ruby SQLite Insert

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 = []

# 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

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?

+5
source share
1 answer

, - SQL . :

# Ditch the gsub in prepare_for_insert and...
db  = SQLite3::Database.new('/Users/michael/catalog.db')
ins = db.prepare('insert into catalog (column_name) values (?)')
string.each { |s| ins.execute(s) }

column_name , ; INSERT, . , ins.execute.

prepare execute , , " , PHP 1999 .

, CSA , XSV ( ), , , , .

+10

All Articles