sqlite - How do I pass a variable into a prepared statement in Ruby? -
i have method in ruby query database , print out data, , i'm trying use prepared statement instead.
here's functioning method without prepared statement:
def print_state_speakers(*states) puts "state speakers" state_string = "'#{states.*"', '"}'" state_speakers = $db.execute(" select name, location congress_members location in (#{state_string}) order location") state_speakers.each { |rep, location| puts "#{rep} - #{location}" } end here's attempt @ same method using prepared statement:
def print_state_speakers(*states) puts "state speakers" state_string = "'#{states.*"', '"}'" begin pst = $db.prepare "select name, location congress_members location in (?) order location" state_speakers = pst.execute state_string end state_speakers.each { |rep, location| puts "#{rep} - #{location}" } end here's call method:
print_state_speakers('nj', 'ny' , 'me', 'fl', 'ak') when run file 1st method shows data, when use 2nd, shows nothing. doesn't throw error. feel syntax needs different account string being passed in, i've been searching online , messing around while , can't work. insight how fix prepared statement appreciated.
when this:
pst = $db.prepare "select name, location congress_members location in (?) order location" state_speakers = pst.execute state_string the pst.execute call escape , quote state_string other string. state_string isn't single string, sql list represented (ruby) string you'll end double quoting everything.
an easy solution use string interpolation add appropriate number of placeholders , let sqlite3::statement deal quoting itself:
placeholders = ([ '?' ] * states.length).join(',') pst = $db.prepare "select name, location congress_members location in (#{placeholders}) order location" state_speakers = pst.execute states this use of string interpolation safe because know in placeholders.
Comments
Post a Comment