Dump that table

In a previous post we have seen how to connect to a database using the Perl DBI module, here we write a subroutine, to be called after the connection has been estabilished and before disconnecting, to actually perform a query.

Assuming we have a table named t in the current database schema, here is it:

sub dumpThatTable
my $dbh = shift;
my $sth = $dbh->prepare("select * from t");
print "An error occurred: ".$sth->errstr()."\n";

my @row;
print "@row\n" while(@row = $sth->fetchrow_array());
print "An error occurred: ".$sth->errstr()."\n" if $sth->err();

The subroutine expects to be called with a valid database handle as a parameter, that we extract and put in the local variable $dbh. Then we prepare a SQL statement, putting the result in another local variable, $sth. We try to execute the statement and, in case of success, we loop calling fetchrow_array() on the statement to get the next row and simply printing it.

No comments:

Post a Comment