Wednesday, November 05, 2008

Perl: Connecting to MSSQL with DBI

I need to provide statistics of top 10 Network status for the past 24 hours. All the data is stored in a database. Using a Perl Module; DBI I, i came out with this script. How to communicate with Database using Perl can be summarized by the picture below:



Using this script, i managed to query Top 10 statistic and dumped the data into xml format to generate graph using Flash Graphing tool.

#!/usr/bin/perl

use DBI;
use POSIX 'strftime';

#Define yesterday date
my $yesterday = strftime "%Y-%m-%d",localtime(time - (24*60*60));
my $filename = strftime "%Y%m%d",localtime(time - (24*60*60));

#Creating XML file for Top 10 Ports
my $file="attack$filename.xml";

open ( my $FILE, ">> $file") or die "Cannot open file";

#Colors Array for Graph
@colors =( "AFD8F8", "F6BD0F","8BBA00","FF8E46","008E8E","D64646","8E468E","588526","B3AA00","008ED6");
$dbh = DBI->connect('dbi:Sybase:192.168.200.6',myadmin,mypasswordisharewithu);
die "Unable to connect: $DBI::errstr\n"
unless (defined $dbh);

# Querying the Top 10 Ports from the database
my $sql = qq { SELECT whatever yadayada };

$sth = $dbh->prepare ( $sql ) or

die "Unable to prepare databases query: ".$dbh->errstr."\n";

$sth->execute or
die "Unable to execute database query: ".$dbh->errstr."\n";

#Print into file
$value=0;

print $FILE " \n";

while ($aref = $sth->fetchrow_arrayref) {




$sth->finish;

$dbh->disconnect or
warn "Unable to disconnect: ".$dbh->errstr."\n";

No comments: