I have a Perl script which retrieves data from MySQL Database. this is the code:
sub startSession{
my $self = shift;
my $dsn = "dbi:".$self{platform}.":".$self{database}.":".$self{host}.":".$self{port};
print "$dsn\n" ;
$self{dbHandle} = DBI->connect($dsn,$user,$password);
}
I have provided every information from an external file. I get the error message
DBI connect('dbname:**.**.**.**:3306','',...) failed: Access denied for user 'root'@'dbserver' (using password: NO) at line 89
Can't call method "prepare" on an undefined value at at line 97
I am very sure the root can connect from any host and the password is also correct.
The key part of the warning that I see is " using password: NO ". Check that the password is being set properly.
First, your immediate problem, is as @Sinan Ünür says, that you need to change $self{platform}
to $self->{platform}
, etc.
Your second immediate problem is that it appears you're getting $user
and $password
from nowhere (they are not passed to the function, so they are undefined unless they are global variables), which would explain the using password: NO
part of the error. Maybe those should be $self->{user}
and $self->{password}
?
You should considering put this at the top of your module, at least during development, to automatically catch errors like these:
use warnings qw(all);
use strict;
But I'd also comment, that from a design perspective, you really ought to treat DSNs as opaque strings. Each database has its own DSN format. So if you ever want to target a different database, you'll need a different DSN format. Or, possibly, someday MySQL will use a different format (it already has two). Either way, it'll be much easier to change it one place, in a configuration file, than to track down each place you concatenate the various pieces together.
Presumably, $self
is a hashref, not a plain hash, and you don't have warnings on. So, turn them on, and use $self->{platform}
etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.