Yashwanth Aluru
Yashwanth Aluru

Reputation: 1193

Perl - DBI cannot connect to MySQL (Access Denied...)

I've the following Perl Script through which I try to connect to my local MySQL Server,

#!/usr/bin/perl

use DBI;
use strict;

my $driver = "mysql"; 
my $host = "localhost";
my $database = "test";
my $dsn = "DBI:$driver:database=$database,host=$host";
my $userid = "root";
my $password = "password";

my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;

my $sth = $dbh->prepare("select from_date,to_date from temp");
$sth->execute() or die $DBI::errstr;
print "Number of rows found :" + $sth->rows;
while (my @row = $sth->fetchrow_array()) {
   my ($from_date, $to_date ) = @row;
   print "From Date = $from_date, To Date = $to_date\n";
}
$sth->finish();

When I run this script, I get the below error every time though I gave all privileges to this MySQL user,

Access denied for user 'root'@'localhost' (using password: YES)

I'm new to Perl, I guess some mistake have been done. Please tell me what's wrong in my code.

Thanks in advance!!

P.S. I'm running this on a Windows machine and I get the same error even on my Ubuntu machine though I specify socket's path there.

Upvotes: 0

Views: 7166

Answers (3)

Himanth Reddy Gurram
Himanth Reddy Gurram

Reputation: 11

Just replace your password from double quotes to single quotes.

In your case, change your password from

my $password = "password";

to

my $password = 'password';

Upvotes: -1

Ravi
Ravi

Reputation: 79

I had faced similar issue. I was using below connection string;

my $dbh = DBI->connect("DBI:mysql:database=db_name;host=db_server_ip", "db_user", "db_password", {'RaiseError' => 1});

password was having "@" symbol within, replacing double quotes (") to single quotes (') solved for me.

my $dbh = DBI->connect("DBI:mysql:database=db_name;host=db_server_ip", "db_user", 'db_password', {'RaiseError' => 1});

Upvotes: 2

rouzier
rouzier

Reputation: 1180

In Mysql the username includes the host of connection.

For instance the same user can have two different passwords depending from where they connect.

Example:

root@localhost is a different user than [email protected]

Try and reset your password? In the mysql console run both of the following command. (Changing 'cleartext password' to your password)

SET PASSWORD FOR 'root'@'%' = PASSWORD('cleartext password');

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('cleartext password');

This will allow both root users to use the same password

Upvotes: 1

Related Questions