Quick DBI refresher

Author: John M. Gabriele | back to index

---

Some example code:

#!/usr/bin/perl

use strict;
use warnings;

use DBI;

my $dbh = DBI->connect(
    "DBI:mysql:db_name:host_name",
    "username",
    "pa55w0rd",
    { RaiseError => 1 }
);



my ( $a, $b, $c ) = $dbh->selectrow_array( "select * from some_table" );



# Yields a reference to an array of references.
my $rows_ref = $dbh->selectall_arrayref( "select * from some_table" );

my @row_refs = @{ $rows_ref };   # An array of refs.
for ( @row_refs ) {
    my @row_elems = @{$_};
    # Now get at each column/element of the row by indexing in.
    my $id      = $row_elems[0];
    my $user_id = $row_elems[1];
    my $foo     = $row_elems[2];
    #...
}



$dbh->do( $some_non_select_statement );



my $sth = $dbh->prepare('select foo, bar from baz where moo = ?');
$sth->execute( $moo );

while ( my @row = $sth->fetchrow_array ) {
    # ...
}
$sth->finish;

# More $sth->prepare / ... / $sth->finish calls may follow.



$dbh->disconnect;