pitachip
pitachip

Reputation: 965

Trouble inserting row into sqlite3 database with ruby library

I am a total newbie. I have a database with a table called OUTPUTS where all columns are of type integer. I am trying to insert a row into OUTPUTS with the following ruby script:

require 'rubygems'
require 'sqlite3'
...
db=SQLite3::Database.new("development.sqlite3")
db.execute( "INSERT into OUTPUTS (user_id,eac,pac,vac,iac,epv,ppv,vpv) VALUES (10,@eac,@pac,@vac,@iac,@epv,@ppv,@vpv);" )

Upon running this script, I do get a new row and the user_id column has a 10 in it as expected, but the rest of the columns are empty even though I verified that all of the variables (@eac, @pac, etc) do indeed contain values. What is wrong with my syntax?

Upvotes: 1

Views: 2385

Answers (1)

muffinista
muffinista

Reputation: 6736

You're sending the names of the variables to sqlite, not their values. This is what you want:

db.execute( "INSERT into OUTPUTS (user_id,eac,pac,vac,iac,epv,ppv,vpv)
VALUES (10,#{@eac},#{@pac},#{@vac},#{@iac},#{@epv},#{@ppv},#{@vpv});" )

But even better would be to use variable binding like this:

db.execute( "INSERT into OUTPUTS (user_id,eac,pac,vac,iac,epv,ppv,vpv) 
VALUES (10,?,?,?,?,?,?,?)",
@eac,@pac,@vac,@iac,@epv,@ppv,@vpv)

(I may have messed up my count there).

Check out How do I use placeholders in an SQL statement? for some more details.

Upvotes: 2

Related Questions