Majinbibo
Majinbibo

Reputation: 159

How can I create a MySQL database from a Perl script?

I'm trying to create a database in Perl but it keeps trying to ask me for a database to use. Here's my code:

my @db_months = qw(JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC);

foreach my $db_month (@db_months)
{
  ## create db
  my $db_name = $db_month.$Year;
  my $dbh = DBI->connect($dns, $user, $password) or die "Unable to connect: $DBI::errstr\n"; 
  my $row = $dbh->do("CREATE DATABASE '".$db_name."' DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;"); 
  $dbh->disconnect(); 
}

Please help.

Upvotes: 2

Views: 5844

Answers (3)

VasaraBharat
VasaraBharat

Reputation: 81

Just simply omit the database=$database;:

$dbh = DBI->connect("DBI:mysql:host=$host;port=$port", $user, $pw);
$dbh->do("create database test") or die "Cannot create database \n ";

Upvotes: 2

ysth
ysth

Reputation: 98398

It really helps to know which line is giving an error and what precisely the error is.

Try using backticks (`) instead of single quotes (') around the database name...

Upvotes: 1

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74232

The server administration function of DBD::mysql can be used:

my $rc = $dbh->func( 'createdb', $db_name, 'admin' );

Upvotes: 0

Related Questions