Reading data from MySQL using Perl DBI

We can use prepare to execute read statements. The process is similar to insert statement, except after calling execute( ) , you need to fetch the resultant data set.

my $dbh= DBI->connect_cached('DBI:mysql: test','username','password',{private_connection_key1 =>'connX'})
$sth= $dbh->prepare( "select * from testtable" ) ;
$sth->execute() ;
print "Number of rows in result set: " . $sth->rows . " \n";
my $names= $sth->{NAME} ;
for ( @$names) {
printf(" %-15s", $_) ;
}
print "\n";
while (my $row_ref= $sth->fetch() ) {
for (@$row_ref) {
printf(" %-15s", $_) ;
}
print "\n" ;
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.