Hello,
I am new to Perl programming. Below is piece of perl code I have written to
browse through available drivers and list the databases available for each
driver.
My question is if a specific database is present, I would like to drop and
re-create it. One way of doing that is to connect to it which returns back a
database handle and with the help of that handle, just execute a do with DROP
DATABASE followed by CREATE DATABASE. However, what if database doesnt exist,
how to create it without obtaining any kind of database handle?
Any help would be greatly appreciated!!!
#!/usr/local/bin/perl
#
# ch04/listdsns: Enumerates all data sources and all
# installed drivers
#
use DBI; # for database
use DB;
use DBD::ODBC;
my $databaseName = "july";
my $driverName = "ODBC";
### Probe DBI for the installed drivers
my @drivers = DBI->available_drivers();
my $drh = DBI->install_driver('ODBC');
my $dbiPart;
my $odbcPart;
my $datasrcName;
die "No drivers found!\n" unless @drivers; # should never happen
### Iterate through the drivers and list the data sources for
### each one
foreach my $driver ( @drivers ) {
print "Driver: $driver\n";
my @dataSources = DBI->data_sources( $driver );
foreach my $dataSource ( @dataSources ) {
if($driver eq $driverName)
{
#Slice it to exactly find the database name.
($dbiPart,$odbcPart,$datasrcName)=split(/:/,$dataSource);
print "\tDatabase Name: $datasrcName\n";
if($datasrcName eq $databaseName)
{
#database exists, so we should FIRST
# CONNECT to it
# DROP and RE_CREATE it
$dbh = DBI->connect ("DBI:mysql:database=$databaseName",
'','');
$dbh->do ( qq (DROP DATABASE $databaseName) );
$dbh->do ( qq (CREATE DATABASE $databaseName) );
}
else
{
How do I create database? Below statement
gives an error ($dbh is undefined, so cannt call "do")
#$dbh->do ( qq (CREATE DATABASE $databaseName) );
}
}
else
{
print "\tData Source is $dataSource\n";
}
}
print "\n";
}