MySQL access, parameter binding

Hi all!

So I have another noob question. In fact - two questions:

  1. What’s best way to access MySQL? “require ‘mysql’”? “require ‘dbi’”?
    I’m confused… DBI doesn’t seem to return the number of rows matched by
    a query (even though sth.rows method is there - it always returns 0).

  2. How do I pass an array to bind? For example:

bindParams = [ 1, 2 ]
sth = dbh.prepare( "select * from table where a = ? and b = ? " )
sth.execute( bindParams )

That’s how I, having mostly developed software in Perl, would do it. But
apparently that’s not how DBI expects it - it does not accept an array,
it seems to expect me specifically list all individual values (as in
sth.execute( bindParams[0], bindParams[1] ) - what am I missing?

Thanks!

I can’t tell about the first question, but for second you can use the
splat operator.

bindParams = [ 1, 2 ]
sth = dbh.prepare( "select * from table where a = ? and b = ? " )
sth.execute( bindParams )

sth.execute( bindParams[0], bindParams[1] )

Use this: sth.execute(*bindParams). The star (called “splat” in this
context) will “split” the array into individual components, and pass
all of them as arguments to the method. You can use the same operator
for example for “destructuring assignment”:

a, b = * ‘some text’.split(/ /)
#=> a = ‘some’, b = ‘text’

– Matma R.

Bartosz Dziewoński wrote in post #1044590:

Use this: sth.execute(*bindParams). The star (called “splat” in this
context) will “split” the array into individual components, and pass
all of them as arguments to the method. You can use the same operator
for example for “destructuring assignment”:

a, b = * ‘some text’.split(/ /)
#=> a = ‘some’, b = ‘text’

Awesome! THANK YOU!!! :slight_smile:

Looks like it’s going to be a long way until I’m as good at Ruby as I am
at Perl (not that I’m 10 out of 10 in Perl anyways… :slight_smile: )