A Short Perl DBI Example
Listing D.1 connects to a server, prepares a query with a placeholder, binds a number of values to this placeholder, and then loops through each row and each query to display the results.Listing D.1: example.pl
#!/usr/bin/perl -w
use strict; # you don't have to use strict, but you should!
use DBI; # the main module
# set variables with the connection details
my $hostname = 'localhost';
my $database = 'firstdb';
my $username = 'guru2b';
my $password = 'g00r002b';
#Connect to the database
my $dbh = DBI->connect("dbi:mysql:$
database:$hostname", $username, $password);
# Define and prepare the query, with the ? specifying a bind variable.
my $sql = q{SELECT first_name,surname FROM customer WHERE id=?};
my $sth = $dbh->prepare($sql);
# Create an array of id's to use to replace the placeholder
my @ids = (1,4,5,6);
# Loop through the array and execute the query
for(@ids) {
$sth->bind_param(1, $_, SQL_INTEGER);
$sth->execute();
my( $first_name, $surname);
$sth->bind_columns(undef, \$first_name, \$surname);
# Loop through the rows returned and display the results
while( $sth->fetch()) {
print "$first_name $surname\n";
}
}
$sth->finish();
$dbh->disconnect;