Showing posts with label perl. Show all posts
Showing posts with label perl. Show all posts

Wednesday, August 31, 2011

How to read from database using Perl


Below is the perl script to write into Database.

Assumption: one database 'databasename' exists on host m/c, which has a table with name 'tablename' which further has at least one column with name 'date'.

===================
#!/usr/bin/perl
print "Content-type: text/html\n\n";

use DBI;
use CGI;

# CONFIG VARIABLES
$host = "fdb2.eu.pn";
$database = "databasename";
$dsn = "DBI:mysql:database=$database;host=$host";
$user = "someuser";
$pw = "somepassword";

# DB CONNECT
$dbh = DBI->connect($dsn, $user, $pw) or print "connect failed";
if ($dbh)
{
my $sth = $dbh->prepare("select * from tablename");
$sth->execute();
my $nf=$sth->{NUM_OF_FIELDS};
print "Num of fields = ". $nf;

if ($nf != 0){
my $id;
while($id=$sth->fetchrow_hashref()){
print "$id->{date}\n";
}
}
}