GUFE Walkthrough: Part 3
November 8, 1999
sub openDB {
#open connection to database
my ($DBD,$dbase,$dbuser,$dbpassword)=@_;
my $dbh = DBI->connect("dbi:$DBD:$dbase",$dbuser,$dbpassword)
|| die "could not connect to database!";
return $dbh;
} #end openDB
Establishing the connection to the database is fairly simple,
and that's just what the &openDB subroutine
does. Four parameters are sent to this subroutine when it is
called -- the DBD protocol to use (such as "mysql"
or "ODBC"), the database to connect to (such as
"Clients"), and if necessary a username and
password. Some databases, such as those in MySQL,
can
be protected requiring login. You can see that parameters
passed to a subroutine wind up in the Perl built-in
variable @_, a list of each value sent in.
If for some reason the connection should fail, the
subroutine "dies", meaning that it exits to the
browser with an error message.
sub sendSQL {
#send SQL query
my ($sqlstatement,$dbh)=@_;
my $sth = $dbh->prepare($sqlstatement);
$sth->execute ||
die("Could not execute SQL statement ... maybe invalid?".
"<br>Here is the statement that choked: $sqlstatement");
return $sth;
}#end sendSQL
The &sendSQL subroutine, while extremely
important to GUFE, is also quite simple. That's because
interpreting and processing SQL statements is the job of
the database itself. In short, &sendSQL receives
the SQL statement and the database handle. Then, using
standard DBI syntax, it prepares and executes the SQL statement
at the database engine. The final result of this is a
statement handle, which is returned from the subroutine,
and which we later use to access the actual data returned
by the database in response to the query. It is with
this statement handle, $sth, that we'll do much of
our work.
GUFE Walkthrough: Part 2
The Perl You Need to Know
GUFE Walkthrough: Part 4
|