Listing stock items

The shell of a stock-listing script is available in your exercises/acme/ directory as stocklist.pl.

#!/usr/bin/perl -w
use strict;
use DBI;

my $driver = 'mysql';
my $database = 'trainXX';
my $username = 'trainXX';
my $password = 'your_password_here';

my $dsn = "DBI:$driver:database=$database";
my $dbh = DBI->connect($dsn, $username, $password) 
        || die $DBI::errstr;

my $sql_statement = "select * from stock_item";
my $sth = $dbh->prepare($sql_statement);
$sth->execute() or die ("Can't execute SQL: " . $dbh->errstr());

while (my @ary = $sth->fetchrow_array()) {
        print <<"END";
ID:            $ary[0]
Description:   $ary[1]
Price:         $ary[2]
Quantity:      $ary[3]
END
}

$dbh->disconnect();

  1. Fill in the variables indicated ($database, $sql_statement, etc)

  2. Test your script from the command line

  3. Sort the output in alphabetical order by Description

Advanced exercises:

  1. If you are familiar with Perl references, convert the script to use fetchrow_hashref()

  2. Ask the user to specify a field to sort by, either as a command line argument or on STDIN. If the sort order parameter is given, use it to change the sort order in your SQL statement and re-output the result, otherwise default to something sensible such as ID