1

I want to execute my INSERT strings within a Ruby file that has the following array:

names_arr = ["Jack", "Susan", "Peter"]

In the same Ruby file, I've required the SQLite3 gem and have this code:

names_arr.each do |each_name|
  db.execute('INSERT INTO users (name) VALUES ("#{each_name}");')
end

I am expecting this in my "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, but I've tried a lot of different things and can't figure out where I'm wrong.

I am using SQLite3 and Ruby.

2
  • Try this db.execute("INSERT INTO users (name) VALUES (#{each_name});" Commented Oct 6, 2013 at 21:16
  • 1
    Double quotes for interpolation Commented Oct 6, 2013 at 21:28

1 Answer 1

2

You have several problems in this code:

names_arr.each do |each_name|
  db.execute('INSERT INTO users (name) VALUES ("#{each_name}");')
end
  1. You're trying to use Ruby's string interpolation inside a single quoted string but string interpolation only works in double quoted strings (and heredocs, %Q{...} strings, regex literals, ...).
  2. Standard SQL uses single quotes for string literals, not double quotes. Some databases let you get away with double quotes but it is a really bad habit to get into.
  3. You shouldn't use string interpolation to build SQL anyway, you're not hacking PHP in 1999 so you should use placeholders and let the database library deal with the quoting.

The SQLite driver's execute understands ? placeholders so you can say this:

names_arr.each do |each_name|
  db.execute('INSERT INTO users (name) VALUES (?)', each_name)
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this was most helpful! Also found this link that helped with inserting multiple columns of data with ? placeholders.
FYI, I just learned that another term for placeholders mu is using is "sanitation replacement."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.