I am trying to build a few functions into a perl script to create, delete and grant permissions on mysql databases.
At the moment, I try to grant permissions for a user to specified database, like this:
use DBI;
my $dbname=$_[1];
my $dbh = DBI->connect("dbi:mysql:", $sqluser,$sqlpass) or die "Unable to connect: $DBI::errstr\n";
.....
my $username=@unp[0];
my $dbname=@unp[1];
my $db_com="GRANT ALL ON ".$dbname.".* TO '".$username."'\@'localhost'";
my $sth = $dbh->prepare($db_com);
$sth->execute
or die "SQL Error: $DBI::errstr\n";
print "Permissions granted\n";
This works if the user exists.
While trying similiar code for CREATE USER, and DROP USER, it works efficiently, creating, or deleting them as requested, or throwing mysql syntax errors if the user doesnt exist. But while granting privileges, I am set back by the fact that the command executes even if the database does not exist.
In fact on mysql prompt, if the sql query is executed, it returns:
Query OK, 0 rows affected (0.00 sec)
I need a way to discover whether the database does not exist, and prompt the user to provide a correct database name.