Listing 1. retrieve-today-birthday.pl, which uses DBI to retrieve the names of people in our addressbook table whose birthdays are today.
#!/usr/bin/perl
use warnings; # Perl 5.6.x version of "-w" option
use strict;
use DBI;
# Set up some basic variables
my $dbname = 'addressbook';
my $username = 'reuven';
my $password = '';
# What name should we look for?
my $look_for_name = $ARGV[0];
die "You didn't enter a name to look for "
unless $look_for_name;
# Connect to the database
my $dbh = DBI->connect
("dbi:Pg:dbname=addressbook",
$username, $password,
{RaiseError => 1, PrintError => 1,
AutoCommit => 1});
# Make sure that we successfully connected to
# the database
die "No connection to the database: '$DBI::errstr' "
unless $dbh;
# Add % to the front and back, for an SQL regexp
$look_for_name = "%" . $look_for_name . "%";
# Create the SQL query
my $sql = "SELECT first_name, last_name, birthday ";
$sql .= " FROM People ";
$sql .= " WHERE (first_name LIKE ?)
OR (last_name LIKE ?) ";
# Prepare the query
my $sth = $dbh->prepare($sql);
# Execute the query
$sth->execute($look_for_name, $look_for_name);
# Iterate through returned rows
while (my $row_ref = $sth->fetchrow_arrayref)
{
my ($first_name, $last_name, $birthday)
= @{$row_ref};
print "$first_name $last_name
(birthday: $birthday)\n";
}
# Make sure that some rows were returned
if ($sth->rows == 0)
{
print "No one in the addressbook matches
that pattern.\n";
}
# We're done with this SQL statement
$sth->finish;
# Close our connection to the database
$dbh->disconnect;
Copyright © 1994 - 2019 Linux Journal. All rights reserved.