lunes, 29 de abril de 2013

Perl: Read a Table from database using DBI

¿How to read a Table from database using DBI? 

#!/usr/bin/perl -w

use strict;
use warnings;
use DBI;

use constant DATABASE => "mydatabase";
use constant HOSTNAME => "myhostname";
use constant USERNAME => "user";
use constant PASSWORD => "123";

my $dbh = db_connect();

print "\nRead MyTable table : \n";

my $rows = read_table($dbh);
my $affected_rows = print_table($dbh, $rows);
print "Affected rows: $affected_rows: \n";

#
sub read_table {
    my $dbh = shift;

    my $sql1 = qq(
        SELECT * FROM MyTable

    );
    my $sth1 = $dbh->prepare_cached( $sql1 );
    $sth1->execute();
    my $sql_return = $sth1->fetchall_arrayref( {} );
       
    return $sql_return;
}

#
sub print_table {
    my $dbh = shift;
    my $rows = shift;

    foreach my $row (@$rows) {       
          print "$row->{
columnName_01}\n";
          print "$row->{columnName_02}\n";  
        }

  my $arraySize = scalar (@$rows);
  return $arraySize;
   
}
   
sub db_connect {
   
    my $db   = DATABASE;
    my $host = HOSTNAME;
    my $user = USERNAME;
    my $pass = PASSWORD;

    my $dbh = DBI->connect(
        join(':', 'dbi:mysql', $db, $host), $user, $pass,
        { AutoCommit => 1, PrintError => 1, RaiseError => 1 },
    );

    return $dbh;
}

No hay comentarios:

Publicar un comentario