I have an example string “Canon PowerShot 12.1-Megapixel” and when I run the following code, it seems to fail:
db.execute "CREATE TABLE IF NOT EXISTS Products( id INTEGER PRIMARY KEY, stockID INTEGER, Name TEXT )"
id = 12345
name = "Canon PowerShot 12.1-Megapixel"
db.execute( "INSERT INTO Products ( stockID, Name ) VALUES ( #{id}, #{name} )" )
The error code is:
C:/Ruby/Ruby193/lib/ruby/gems/1.9.1/gems/sqlite3-1.3.6-x86-mingw32/lib/sqlite3/d
atabase.rb:91:in `initialize': near "PowerShot": syntax error
(SQLite3::SQLExcep tion)
from C:/Ruby/Ruby193/lib/ruby/gems/1.9.1/gems/sqlite3-1.3.6-x86-mingw32/
lib/sqlite3/database.rb:91:in `new'
from C:/Ruby/Ruby193/lib/ruby/gems/1.9.1/gems/sqlite3-1.3.6-x86-mingw32/
lib/sqlite3/database.rb:91:in `prepare'
from C:/Ruby/Ruby193/lib/ruby/gems/1.9.1/gems/sqlite3-1.3.6-x86-mingw32/
lib/sqlite3/database.rb:134:in `execute'
from E:/Documents/Cowboom/scraping/DBDOTDList.rb:48:in `<main>'
Any idea why this dies after “PowerShot”?
There are no quotes around the string that you are creating. So the string is actually coming out as:
As you can see, that is invalid SQL; it will try to interpret
Canon PowerSho 12.1-Megapixelas part of the SQL statement, not as a string.You could try to fix this by putting quotes around the variable interpolations:
However, this is a bad idea in general. If the string winds up containing a
', then that will end the string within the SQL statement, causing an error (or worse, if an attacker does it, an SQL injection exploit; see this comic for an amusing example). You should generally avoid trying to build an SQL query by interpolating or appending strings; you may think that you could filter out or quote the wrong characters, but that is actually quite difficult to do.Instead, you should use bound parameters for any variable data that you are passing into your SQL statement:
See the sqlite3-ruby documentation for more information and examples.