|
Use Perl DBI For Database Access
|
|
|
|
|
Contributed by Chad Brandt
|
|
|
|
Saturday, 03 July 2004
For many perl programs I write I need to access a relational database. Perl provides the DBI library to access many databases.This is an example program that shows how you can access MySql and Postgresql from within a perl program
#!/usr/bin/perl ############################################################ # This is an example of connecting to a MySQL database # and a postgresql database using perl DBI # # This requires the DBI:mysql and DBI:Pg modules # ############################################################ use DBI; use strict;
my @row; my $dbh; my $sth;
# This is a mysql example displaying all rows from the user table $dbh = DBI->connect('DBI:mysql:mysql:localhost', 'root', 'password'); $sth = $dbh->prepare(qq{ select * from user}); $sth->execute(); while(@row = $sth->fetchrow_array()){ print "@rown"; } # close the connection $dbh->disconnect();
# This is a postgres example displaying all rows from the user table $dbh = DBI->connect("dbi:Pg:dbname=test;port=5432;user=postgres;password=mypassword); $sth = $dbh->prepare(qq{ select * from user_}); $sth->execute(); while(@row = $sth->fetchrow_array()){ print "@rown"; }
$dbh->disconnect();
exit(0);
|
Perfect Written by Guest on 2008-11-14 07:45:01 This was simple and to the point |
Powered by AkoComment 1.0 beta 2! |