How to insert Ruby array items into SQLite? -
i want execute insert
strings within ruby file has following array:
names_arr = ["jack", "susan", "peter"]
in same ruby file, i've required sqlite3 gem , have code:
names_arr.each |each_name| db.execute('insert users (name) values ("#{each_name}");') end
i expecting in "users" table:
id name 1 jack 2 susan 3 peter
instead, i'm getting this:
id name 1 #{each_name} 2 #{each_name} 3 #{each_name}
it's clear i'm not interpolating properly, i've tried lot of different things , can't figure out i'm wrong.
i using sqlite3 , ruby.
you have several problems in code:
names_arr.each |each_name| db.execute('insert users (name) values ("#{each_name}");') end
- you're trying use ruby's string interpolation inside single quoted string string interpolation works in double quoted strings (and heredocs,
%q{...}
strings, regex literals, ...). - standard sql uses single quotes string literals, not double quotes. databases let away double quotes bad habit into.
- you shouldn't use string interpolation build sql anyway, you're not hacking php in 1999 should use placeholders , let database library deal quoting.
the sqlite driver's execute
understands ?
placeholders can this:
names_arr.each |each_name| db.execute('insert users (name) values (?)', each_name) end
Comments
Post a Comment