|XP is just a number|
Reading from a databaseby stephen (Priest)
|on Apr 14, 2000 at 02:41 UTC||Need Help??|
The easiest way to read data from a database with Perl is by using the DBI module. DBI is available from CPAN, and is quite possibly already installed on your system.
For those in a hurry, here's the quick answer:
DBI is Perl's DataBase Interface. There are many different databases: Oracle, mSQL, MySQL, Ingres... even files containing data separated by columns could be considered databases. DBI works with practically all of them.
To get information from a database, typically we have to:
This document assumes that you know enough about SQL to write your own SELECT statement. I don't go into too much detail on the internals of DBI; get the DBI book for more information.
How DBI Works
There are many different databases out there, and each one has its own way of communicating. For that reason, DBI requires a database driver module to talk to the database. The driver module handles all of the details about connecting to and communicating with the database. DBI sits on top of the driver; its job is to make reading from (and writing to) all databases as similar as possible. That way, if your project grows from something that could be handled with mSQL to something needing Oracle, you can make that change without altering the code very much.
Database driver modules are Perl modules like any other, and often they contain documentation. They are all inside the root package DBD. So, to get information on an Oracle driver you've installed, you can type:
Other than installing the module, and possibly reading the documentation, you rarely need to deal directly with the database driver module. DBI handles all of that.
Connecting To The Database
In order to get information out of the database, you must first connect to it. Since DBI deals with many different kinds of databases, you need to tell it what kind of database you have before it can connect to it. Also, you'll need to give it your username and password.
The string 'DBI:mysql:my_database' is the connect string. Different databases accept different formats for the connect string, but the usual format is:
The 'driver' is the type of database system you have: 'Oracle', 'mysql', etc. 'Database' is the name of the database. Some database systems don't have names for individual databases; you can leave those blank.
'my_username' and 'my_password' are the username and password that you use to access the database system. These are not the username and password that you use to log in to your account! Some databases don't need a special username and password; in that case, leave them out. Check out the driver documentation for details.
If the connection fails for some reason, connect() will return false, and DBI will put its error message into $DBI::errstr. It's important to include that 'or die' in the statement, or else if there are any problems with your database, they won't show up until deep inside your program, and you'll waste hours trying to debug it.
Preparing And Executing The Query
Next, you need to create a query to send to the database, then send it to the database.
You prepare a query using the prepare statement. Its syntax is pretty simple:
$sth here is a statement handle. You're going to use it to get all of your information from the database.
Next, to send your query to the database, use the execute() method on the statement handle:
Again, it's important to put the "or die" on the end of the statement.
Reading Data From The Database
Now that you've sent the query, your database will grind a bit and spit out the rows that satisfy it. To read the data from those rows, you need to fetch them, one row at a time. There are three methods that you can use to fetch the data: fetchrow_array(), fetchrow_arrayref(), and fetchrow_hashref(). These methods are all similar. Each time that you call them, they'll return the data for a row returned by the query. When there are no more rows left, they'll return a false value. Fetchrow_array() returns each row as an array of scalar values; it returns an empty list when it's done. It's generally used like so:
Fetchrow_arrayref() is similar. It returns each row as a reference to an array. This method is slightly more efficient than calling the fetchrow_array() method, since we don't need to spend time and energy copying the array values. Here's how it's used:
Fetchrow_hashref is one of the most flexible of these methods. It returns each row as a reference to a hash. The keys of the hash are the names of the columns, and the values are the values of that column for this particular row. Use it like so:
With this flexibility comes some inefficiency, though-- the computer uses some time creating the hash table, and looking things up in the hash takes longer than finding them in an array. Still, it's very useful for applications where efficiency isn't super-important.
Which brings us to...
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:
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:
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:
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.
So, a better way of doing the above would be:
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.