Monday, August 13, 2007

How to create a MySQL table using Perl Script.
Following way is the method which can create MySQL table using perl script.
It uses DBI perl module. You can get more information about DBI module by visiting
http://www.cpan.org
Changing the variables, try and see how is it easier.

#!/usr/bin/perl

use DBI;
use strict;

my $DB_NAME = 'nipuna';
my $USER_NAME = 'root';
my $PASSWORD = '';

my $dbh = DBI->connect('DBI:mysql:$DB_NAME','$USER_NAME','$PASSWORD',{RaiseError => 1});

if($dbh){
print "Sccessfully connected to the database! \n";
}
my $sql = "CREATE TABLE tblTest(fname varchar(30), age int(2))";
my $query = $dbh->do($sql);
if ($query == 0){
print "Table was created\n";
}else{
print "Not created\n";
}
$dbh->disconnect;

Following script explain how to execute a MySQL query using perl script.

#!/usr/bin/perl

use DBI;
use strict;

my $DB_NAME = 'nipuna';
my $USER_NAME = 'root';
my $PASSWORD = '';

my $dbh = DBI->connect('DBI:mysql:$DB_NAME','$USER_NAME','$PASSWORD',{RaiseError => 1});

if($dbh){
print "Sccessfully connected to the database! \n";
}
$query = $dbh->prepare("SELECT * FROM tblTest");
if (defined($query)){
$query->execute();
}else{
print "Could not execute the query! \n";
}
my @row;
while (@row = $query->fetchrow_array()){
print "$row[2]\n";
}
$dbh->disconnect;

1 comment: