Lexington Perl Mongers
September, 1999
You can download DBI, and your appropriate DBD, from CPAN, and do the standard:
perl Makefile.PL make make test make install
If you are running Perl on Windows, go to a DOS prompt, and type:
ppm install DBI ppm install DBD::ODBC
And, if you're on a Unix system, and have the CPAN module set up correctly, you can type:
perl -MCPAN -e 'install DBI' perl -MCPAN -e 'install DBD::mysql'Substitute for 'mysql' whatever database you are interested in using.
#!/usr/bin/perl
use DBI;
$dbh = DBI->connect('DBD:mysql:students', 'username', 'password');
$sth = $dbh->prepare("select fname, lname, studentID from student
where fname = 'John'
order by lname");
$sth->execute;
$sth->bind_columns(undef, \($fname, $lname, $id));
while ($sth->fetch) {
print "$lname, $fname: $id\n";
}
connect establishes a connection to the database.prepare sends a SQL query to the database, so that it can optimize the query when you come around to running it.
execute runs the query.
bind_columns associates variables with the return columns of the query, automatically putting the data into those variables when you do a fetch.
fetch gets the next row from the query. It returns false if there are no more rows.
There are a number of other ways to retreive data. One particularly useful way (although substantially slower than bind_columns) is the fetchrow_hashref method:
$sth = $dbh->prepare("select * from students");
$sth->execute;
while ($student = $sth->fethrow_hashref) {
print "$student->{fname} $student->{lname} is a $student->{year}.\n";
}
This is useful when you are doing a select *, and want to refer to the fields by name in a hash. This might make your code more readable, and has the additional advantage that all of your data is in one handy data structure that you can pass around. Hashrefs are nice.
pod2html to generate HTML documentation.