Wednesday, November 3, 2010

Perl database interface DBI

http://www.perl.com/pub/1999/10/DBI.html
# db settings
my $db = "mydbname";
my $host = "127.0.0.1";
my $port = 3306;

# connect
my $dsn = "DBI:mysql:database=$db;host=$host;port=$port";
my $fosdb = DBI->connect( $dsn, $user, $pass) or die ( "Couldn't connect to database: " . DBI->errstr . "\n";

# Read the matching records and print them out          
          while (@data = $sth->fetchrow_array()) {
            my $firstname = $data[1];
            my $id = $data[2];
            print "\t$id: $firstname $lastname\n";
          }
my $sth = $dbh->prepare('SELECT age FROM people WHERE id = ?')
            or die "Couldn't prepare statement: " . $dbh->errstr;
$sth->execute($id) 
            or die "Couldn't execute statement: " . $sth->errstr;
$dbh->disconnect;

No comments: