Reputation:
I have this small ruby script that collects data and then save them in a hash and then stores them in a sqlite db.
The hash looks like this:
@track = {:name => "Chris Brown", :song => "Sweet Love", :time => "3:20", :album => "Fortune" }
And I have a method that save this hash into a sqlite database:
def add_db
db = SQLite3::Database.new("playlist.sqlite")
sql = "INSERT INTO tracks (name, song, time, album)" +
"VALUES(#{@track[:name]}, #{@track[:song]},#{@track[:time]}, #{@track[:album]})"
db.execute(sql)
db.close
end
But I get this error: initialize': near "Playlist": syntax error (SQLite3::SQLException)
Is this the rigth way to save hash values into a sqlite3?
Upvotes: 1
Views: 1660
Reputation: 434985
Your problem is that you're not quoting anything that you're inserting so SQLite ends up seeing things like this:
insert into tracks (name, song, time, album) values (Playlist, ...)
and that's not valid SQL. You should use placeholders:
db.execute(
'insert into tracks (name, song, time, album) values (?, ?, ?, ?)',
@track[:name], @track[:song], @track[:time], @track[:album]
)
You can also use ActiveRecord but somethings that's too heavy for a simple data importing script.
Upvotes: 2