How to connect to a database using Perl
Document Sample


How to connect to a database using Perl.
First load the DBI module:
my $dbh = DBI->connect('DBI:Oracle:payroll');
or die "Couldn't connect to database: " . DBI->errstr;
In this case the type of database is an Oracle database, and the database name is payroll.
The second line is if the connection can not be made, the program reports it could not
connect and dies.
If you need to use a password/username:
my $dbh = DBI->connect('DBI:Oracle:payroll', 'username', 'password')
or die "Couldn't connect to database: " . DBI->errstr;
Running queries:
my $sth = $dbh->prepare('SELECT * FROM people WHERE lastname = ?')
or die "Couldn't prepare statement: " . $dbh->errstr;
This prepares the query, the ‘?’ will be filled in later by another statement.
Prepare an array to collect the data:
my @data;
Execute a query:
$sth->execute($lastname) # Execute the query
or die "Couldn't execute statement: " . $sth->errstr;
The $lastname would have been collected from the user for what last name they would
want to search for, it replaces the ‘?’ in the prepare statement.
Making sense of the data returned:
while (@data = $sth->fetchrow_array()) {
...
}
This statement keeps returning the data into an array, until the fetchrow_array() returns
blanks, at that time it kills the while statement.
If you just want certain things out of the data, then you would make the following
statement to grab just want you want:
my $firstname = $data[1];
my $id = $data[2];
Closing the database connection:
$dbh->disconnect;
Be sure to close your connection to the database, not only does it keep things neat, but
you also don’t want to have ports connected that you don’t have to.
Related docs
Get documents about "