Chapter 2
Connecting to Your Database
Chapter Objectives
- Build simple DBI programs
- Follow the prepare/execute/finish model
- Display the contents of a database table
Lab: A CGI script that:
- connects to a database and dumps one of its tables
- uses SQL: SELECT * FROM title
- uses these DBI routines:
- connect
-- establish connection to remote database -- example:
$dbh = DBI->connect("DBI:$DB_type:test_nile", $DB_login, $DB_password);
- optional: prevent data truncation
-- tell ODBC not to truncate the stream
of data it returns (by default, it returns only
the first 256 bytes) -- example:
$dbh->{'LongReadLen'} = 20000;
- prepare
-- send SQL statement to remote database -- example:
$sth = $dbh->prepare(q{SELECT * from title});
- execute
-- tell remote database to do the SQL statement -- example:
$sth->execute;
- dump_results
-- get the result (zero or more rows)
as an unformatted stream of text
- finish
-- tell remote database to free the resources
used by the previous SQL statement -- example:
$sth->finish;
- disconnect
-- terminate connection to remote database -- example:
$dbh->disconnect;
Dan Keller Technical Services © 2000