Accessing Pervasive.SQL With Perl

Page Last Modified:

Home Links ODBC (DBI) Contact

DBI + ODBC - Fetching Examples 2 - using die to catch errors

use strict;
use warnings;
use DBI;

my $dbHandle = DBI->connect('dbi:ODBC:DEMODATA', '', '') or die "Error: $DBI::err - $DBI::errstr\n";
my $stHandle = $dbHandle->prepare('SELECT Name,Description FROM Course ORDER By Name') or die "Error: $DBI::err - $DBI::errstr\n";

my $ret = $stHandle->execute() or die "Error: $DBI::err - $DBI::errstr\n";

while(my @returnRow = $stHandle->fetchrow_array())
{
print "Name: $returnRow[0], description: $returnRow[1]\n";
}

$stHandle->finish();
$dbHandle->disconnect();

This application will now stop as soon as it fails to initialize a connection, prepare a statement or execute the query. $DBI::err and $DBI::errstr are global variables that hold the last error code and error string. There are still at least a couple of things wrong here the database connection and statement resources are not explicitly freed by the code if die is called, and the default behaviour of DBI is to display a warning in addition to the string displayed by die. We can switch off the warning by setting the PrintError connection attribute to 0 either during creation of the connection:

my $dbHandle = DBI->connect('dbi:ODBC:DEMODATA', '', '', {PrintError=>0})

or after the connection is set up:

$dbHandle->{PrintError} = 0;

The next example shows an alternative way of doing this.

Home Links ODBC (DBI) Contact

All content on this site is copyright
Neil Hughes 2010 - 2017