Once You Know, You Newegg

Access mySQL data Efficiently

Elegance, Efficiency, and Robustness

All of the above is fine when you know precisely what the query will be in advance. What about when you need to create a query where one or two of the variables might change? For example, say that you’re writing an application that looks up prices for furniture in a database. The user enters the name of the item of furniture, the program sends the query to the database, and bammo, you’ve got the price. (Sorry, I’m shopping for sofas right now and getting a bit obsessed.) How do you do it?

Well, one way would be to create a new SQL statement each time you run the query. This will mostly work, but it’s not recommended:

# A bad way of doing it while (my $furniture_name = ) { chomp($furniture_name); my $sth = $dbh->prepare("SELECT price FROM furniture_prices WHERE furniture_name='$furniture_name'") or die "Couldn't prepare: '$DBI::errstr'; stopped"; $sth->execute() or die "Couldn't execute: '$DBI::errstr'"; my ($price) = $sth->fetchrow_array(); print STDOUT "Item: $furniture_name Price: $price\n"; }

What’s the problem with this? (Other than that there’s no user interface.) Well, what if one of the chairs is a “Tess of the D’Ubervilles Chair”? Then we’d suddenly get an error, as the apostrophe would get read as an SQL end-quote. The second problem is efficiency. The computer must waste time in every query preparing a statement which is almost exactly like the statement it ran a second ago.

How can we solve these problems? Well, DBI allows the use of things called placeholders in statements. Placeholders tell the database, “at execution time, we’re going to plug a value into here.” Then, you pass the values to fill into the placeholders using the execute() command. Using placeholders, the code would look like this:

# A better way of doing it my $sth = $dbh->prepare("SELECT price FROM furniture_prices WHERE furniture_name=?") or die "Couldn't prepare: '$DBI::errstr'; stopped"; while (my $furniture_name = ) { chomp($furniture_name); $sth->execute($furniture_name) or die "Couldn't execute: '$DBI::errstr'"; my ($price) = $sth->fetchrow_array(); print STDOUT "Item: $furniture_name Price: $price\n"; }

There, the statement handle is only prepared once, and we pass $furniture_type via the execute() method. Plus, when placeholders are used, DBI and the driver know enough to escape any troublesome characters like “‘”.

All of the above works relatively quickly if there’s only one row in the response. But what if we wanted to print out a list of all of the different kinds of loveseats in the database? One might write something like this:

# One way of reading multiple rows my $sth = $dbh->prepare("SELECT furniture_name, price FROM furniture_prices WHERE furniture_type=?") or die "Couldn't prepare: '$DBI::errstr'; stopped"; while (my $furniture_type = ) { chomp($furniture_type); $sth->execute($furniture_type) or die "Couldn't execute: '$DBI::errstr'"; while ( my ($furniture_name, $price) = $sth->fetchrow_array() ) { print STDOUT "Item: $furniture_name Price: $price\n"; } }

Each fetchrow_array() adds a little bit of extra time. The variable has to be read out of the database, copied to the array, then copied to the database. It’ll work, but you can do it much faster. (And cooler.) How? Well, many databases allow you to bind variables directly to a statement, so that as soon as the row is fetched, the variable is filled in with the column’s value.

You bind a scalar variable to a column using the bind_col() method.

$sth->bind_col($column, \$scalar)

So, a better way of doing the above would be:

# Faster way of reading multiple rows my $sth = $dbh->prepare("SELECT furniture_name, price FROM furniture_prices WHERE furniture_type=?") or die "Couldn't prepare: '$DBI::errstr'; stopped"; while (my $furniture_type = ) { my ($furniture_name, $price); chomp($furniture_type); $sth->execute($furniture_type) or die "Couldn't execute: '$DBI::errstr'"; $sth->bind_col(1, \$furniture_name); $sth->bind_col(2, \$price); while ( $sth->fetch() ) { print STDOUT "Item: $furniture_name Price: $price\n"; } }

That’s the most efficient way of reading from the database. The fetch() call above is really just a handy alias to fetchrow_arrayref(), but since we’re not doing anything with the array reference, it’s clearer to say fetch().

So that’s about it. When you’re done with the database, call $dbh->disconnect() to close the connection. If you need or want more information on DBI, do ‘perldoc DBI’, go to the DBI pages. Programming the Perl DBI is an excellent book by Alligator Descartes and Tim Bunce.

Note 1: Different database drivers sometimes handle connection differently; at time of writing DBD::Pg is one of these. See your database driver documentation for how to connect if you’re having problems connecting.

I’m going to go through some things that I thought were lacking in this tutorial. They aren’t necessary, but are helpful.

Selectrow_array:

One thing many perl coders try to do is make their code as short as possible. One way to shorten the code is to use selectrow_array, instead of fetcrow_array. This is helpful if you are only executing a query once, and only getting one row of data.

my @row = $dbh->selectrow_array(q{SELECT my_data1, my_data2 WHERE furniture_type=?},undef, $furniture_type);

This is an extremely simple, and elegant way of selecting, and will be as optimized as any selectrow, that is executed without binding, as $furniture_type is the data executed.

RaiseError:

I find RaiseError to be extremely helpful for mission critical queries, and the majority of queries are mission critical to a script. Therefore it may be easier to just set RaiseError, and stop using or die.

$dbh = DBI->connect($DBDSN, $DBUser, $DBPassword, {RaiseError => 1});

To unset RaiseError on a query in which you want to specify something else to do, if the query doesn’t work just add the code: $dbh->{RaiseError} = 0;, and set raiserror back to 1, after you are done.

Bind_columns:

my ($furniture_name, $price); chomp($furniture_type); $sth->execute($furniture_type) or die "Couldn't execute: '$DBI::errstr'"; $sth->bind_col(1, \$furniture_name); $sth->bind_col(2, \$price);

You don’t need to bind a specific column here. Instead you can just bind all the columns in order, with bind_columns.
So instead of all that code you can write:

chomp($furniture_type); $sth->execute($furniture_type) or die "Couldn't execute: '$DBI::errstr'"; $sth->bind_columns(\my ($furniture_name, $price));

This gets rid of pre-declaring the variables, and using bind_col twice.

Update: Did some research yesterday and found that bind_columns is faster for *all* queries! Strange, but it seems that bind_columns is faster than a fetchrow_arrayref, even if only one row is being caught. This renders fetchrow_array(ref) obselete in a sense, without using bind_columns, as a few lines of code makes a query much faster, regardless of how many rows are being returned.

Comments are closed.