MySQL: Access denied for user 'userName'@&

2019-02-20 18:52发布

问题:

I am having an issue with creating and grating permissions to a user using phpMyAdmin. I am having a Java swing application and it need to connect to this database.

How I created the user and granted the permission are below, step by step.

  1. Open phpMyAdmin
  2. Go to 'Users' tab.
  3. Click on Add New User
  4. Give the user name, select Any Host as the host (so the % is displayed in its text box), and mention the password. Any host is because remote access required.
  5. Select Select under Global Privileges - Data
  6. Click on Go
  7. Now I am in the Users tab starting page again.
  8. Click on Edit Privileges on my newly created user.
  9. Select the database under Database-specific privileges
  10. Tick everything under Database-specific privileges, Data section.
  11. Click on Go

Now, whenever my Java application connects to this, it gives the below error

java.sql.SQLException: Access denied for user 'userName'@'localhost' (using password: YES)

This is how I connect to the database, in my Java application

con = DriverManager.getConnection("jdbc:mysql://"+ip+":3306/databaseName","user","password");

Here,for the variable ip, I tried both localhost and 127.0.0.1 but still no good. What have I done wrong?

I noticed the connection works fine if I select Localhost instead of Any Host in step 4.

回答1:

  • After you have made your user.
  • Click edit priviliges.
  • Change Any Host for Localhost.
  • Apply your priviliges.
  • Scroll to the bottom and
  • make sure that "keep old one" is selected and press Go.


回答2:

You need to grant permissions to the userName@localhost in mysql.

GRANT ALL PRIVILEGES ON database_name TO userName@localhost IDENTIFIED BY 'password';
FLUSH PRIVILEGES;


回答3:

sometimes, mysql server doesn't get a 'localhost' from a local connection, you should try :

GRANT ALL PRIVILEGES ON database_name TO 'userName'@'theHostName' IDENTIFIED BY 'password';

or in a more risky way:

GRANT ALL PRIVILEGES ON database_name TO 'userName'@'%' IDENTIFIED BY 'password';

and finally

FLUSH PRIVILEGES;


回答4:

Have you set any password for the phpmyadmin. if yes please include that in the password field.or you can try lik this

con = DriverManager.getConnection("jdbc:mysql://"+ip+":3306/databaseName","localhost","");