java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
Asked Answered
S

34

75

The following code:

Class.forName("com.mysql.jdbc.Driver");
Connection m_connection = DriverManager.getConnection("jdbc:mysql://localhost","root","root");

Throws this exception on getConnection():

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1694)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1244)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2397)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2430)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2215)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at db.Database.<init>(Database.java:91)
    at db.Main.main(Main.java:10)

How is this caused and how can I solve it?

EDIT:

    public static void main(String[] args) throws ClassNotFoundException, ServletException, SQLException 
    {

        try
        {
            Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword"); 
            Statement   s = (Statement) conn.createStatement();
            int result = s.executeUpdate("CREATE DATABASE databasename");
        }


        catch ( Exception e)
        {
            e.printStackTrace();
        }
}

Produces :

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1694)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1244)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2397)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2430)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2215)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at db.Main.main(Main.java:19)
Sacrilegious answered 12/8, 2012 at 12:51 Comment(6)
are you able to connect using mysql GUI client like SqlYog or PhpMyAdmin?Clink
@ftom2: Yes , I can access phpmyadmin successfully .Sacrilegious
Are you sure the Username and the Password so provided is right ? Seesm to me there is no such user as root :( Not sure though, but don't you have to provide the Database Name too like Connection con = DriverManager.getConnection("jdbc:mysql://localhost;database=mywebsitedb;user=sa;password=thatstrue;");Arsyvarsy
@GagandeepBali: think once again about it: If the login was wrong, how would the OP be able to access it by phpmyadmin then?Hassan
@Hassan : Actually never used phpmyadmin, though I had used SQLServer sometimes, those fields are autofilled by default, and we forget them. That's why that guess was as comments, else it could become an answer, if I thought that is really the case (which it may or may not be the case). Though since you are offended by that comment, I would be very much wrong in asking the same , my bad :-)Arsyvarsy
There are 2 things you need to establish - are you a valid user, do you have the authority (privileges) to perform the action. Authority takes the form of a specific privilege from a specified host. It is possible to answer both questions before introducing any Java. Personally, I'd use the command line to connect to my sql as the user specified, e.g. 'mysql -uroot -prootpassword', then execute the command 'create database mydb'. If this works you can drop the database and head over to your Java code.Sabec
D
24

As you are creating a database from scratch, you could use:

Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword"); 
PreparedStatement ps = connection.prepareStatement("CREATE DATABASE databasename");
int result = ps.executeUpdate();

Here is an identical scenario.

Denigrate answered 12/8, 2012 at 13:4 Comment(2)
If I don't have any database at all ? and I want to create the database using java code , and NOT manually in phpmyadmin , then databaseName is not relevant ?Sacrilegious
I was working on one of my application, the connectivity between the code and the database was fine. I started getting this error suddenly, dont know why and what to do.Enchain
L
68

This can help you:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '%password%' WITH GRANT OPTION;

Execute it with command line or some GUI tool.

Don't forget to replace %password% with real password.

Lanneret answered 12/8, 2012 at 13:23 Comment(3)
@Lanneret I have successfully executed this query but still not getting rid from this errorSpeleology
@Lanneret Whether the above solution works for the below one also. Here instead of localhost, IP address is mentioned as below java.sql.SQLException: Access denied for user ''@'1.1.22.85' (using password: YES).Sorel
If anyone facing Access Denied problem after applying this solution then you can apply link solution for life easy. ThanksOssetia
L
29

This is specific to Ubuntu 18.04 LTS and MySQL 5.x Followed this link Follow everything from here onwards:

sudo mysql_secure_installation

sudo mysql

Once logged into MySQL then from the MySQL prompt execute these commands:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
FLUSH PRIVILEGES;

Now verify that the table has the password for the root

SELECT user,authentication_string,plugin,host FROM mysql.user;

This solved my issue and now i am able to login.

Loats answered 23/9, 2018 at 4:41 Comment(1)
"Now verify that the table has the password for the root" - and what if it does not? ;)Evangelineevangelism
D
24

As you are creating a database from scratch, you could use:

Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword"); 
PreparedStatement ps = connection.prepareStatement("CREATE DATABASE databasename");
int result = ps.executeUpdate();

Here is an identical scenario.

Denigrate answered 12/8, 2012 at 13:4 Comment(2)
If I don't have any database at all ? and I want to create the database using java code , and NOT manually in phpmyadmin , then databaseName is not relevant ?Sacrilegious
I was working on one of my application, the connectivity between the code and the database was fine. I started getting this error suddenly, dont know why and what to do.Enchain
S
9

I had a similar problem, but the differemce was: I didn't executed my JavaApp from localhost, but from a remote PC. So I got something like java.sql.SQLException: Access denied for user 'root'@'a.remote.ip.adress' (using password: YES) To solve this, you can simply login to phpMyAdmin, go to Users, click add user and enter the host from which you want to execute your JavaApp (or choose Any Host)

Seriocomic answered 20/6, 2015 at 18:16 Comment(0)
K
9

you can use this

   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost:3306/YOUR_DB_NAME";


   static final String USER = "root";
   static final String PASS = "YOUR_ROOT_PASSWORD"; 

  Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);

you have to give the right root password .

Kaiserdom answered 13/10, 2015 at 13:43 Comment(0)
S
6

I had the same issue like below

"java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)". Problem was "WRONG PASSWORD". 

Copy and paste the query as-it-is in the shell to check whether it gives the desired output or not. Small errors consumes more time.

Sclera answered 8/9, 2016 at 20:41 Comment(1)
I had same problem. I was wrong with the password specified in the application.properties. It should be same as your local database password.Rexanna
F
5

This appears to mostly happens when the MySQL username and password are not correct. Check your MySQL username and password.

Forebode answered 29/5, 2018 at 13:17 Comment(1)
Thanks for this. My issue had to do with an incorrect password. I was deploying an app to a Kubernetes cluster, and the password was encrypted in Kubernetes secrets. All I had to do was view the Kubernetes secret in the cluster, de-encrypt the password from base64 to json, which revealed the incorrect password, and then I corrected the password and deployed. This time it worked fine.Shellieshellproof
L
2

You should specify the db you are connecting to:

jdbc:mysql://localhost:3306/mydb
Lanneret answered 12/8, 2012 at 13:0 Comment(0)
A
2

In my case, I created a new user with name admin and used it...

CREATE USER 'admin'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost'
WITH GRANT OPTION;

CREATE USER 'admin'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%'
WITH GRANT OPTION;
Atory answered 9/7, 2022 at 8:10 Comment(0)
T
1

Try it like this....

public static Connection getConnection() throws SQLException{

    String driver = "com.mysql.jdbc.Driver";
    String url    = "jdbc:mysql://localhost:3306/test";
    String username = "root";
    String password = "vicky";            // Change it to your Password
    System.setProperty(driver,"");

    return DriverManager.getConnection(url,username,password);
}
Triphylite answered 12/8, 2012 at 13:0 Comment(1)
Why exactly would it solve the concrete problem? You are not explaining the cause in any way.Hassan
A
1

I was hitting the same issue. Added mysql service port number(3307), resolved the issue.

conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/?" + "user=root&password=password");
Aid answered 5/7, 2013 at 11:21 Comment(0)
S
1

Although this may not be the cause of your issue, you'll get the same error if there are two MySQL services running on the same port. You can check on windows by looking at the list of services in the services tab of Task Manager.

Slug answered 21/6, 2016 at 20:0 Comment(1)
This is a comment, not an answer.Carpous
A
1

This Exception is also caused due to version mismatch of mysql db and your pom.xml/jar.

Make sure your pom.xml/jar version is higher than your mysql db version. Because higher versions are compatible with lower version's, but the same is not true for the inverse.

Solution's for java project

  • Replace the Jar with suitable version.

Solution for maven based

  • Change the dependency Version in pom.xml

Solution for spring boot - Override the spring boot dependency by adding 5.1.5.Final

Amalekite answered 3/11, 2017 at 5:14 Comment(0)
G
1

I am using Spring Boot 2.2.6(Windows) and faced the same issue when I tried the run the application: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

What solved my problem:

  1. Create a new user (from the MySQL workbench or a similar GUI which you might be using)
  2. Grant DBA priviledges (Tick the DBA checkbox) also from the GUI
  3. Run the spring boot application.

Or follow the @evg solution to grant privilegdes from command line in Linux env.

Grearson answered 16/4, 2020 at 6:39 Comment(1)
I am using Spring Boot 2.6.2(Windows) and faced the same issue when I tried your solution but not able to resolve my issue:Anytime
A
1

My application.properties looked something like this

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydb

spring.datasource.username=root

spring.datasource.password=root

The only thing worked for me is to maven clean and then maven install.

Araceli answered 8/9, 2020 at 16:37 Comment(0)
C
1

When I'm running a springboot project, the application.yml configuration is like this:

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/lof?serverTimezone=GMT
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

Notice that there isn't quotation marks around the password. And I can run this project in my windows System.

But when I try to deploy to the server, I have the problem and I fix it by changing the application.yml to:

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/lof?serverTimezone=GMT
    username: root
    password: "root"
    driver-class-name: com.mysql.cj.jdbc.Driver
Cyclosis answered 13/2, 2021 at 13:49 Comment(0)
C
1

Add port number (something like 3306) in:

Connection c = DriverManager.getConnection("jdbc:mysql://localhost:urport","root","root");
Contaminant answered 14/2, 2021 at 13:38 Comment(0)
O
1

Solved! change localhost by 127.1.1.1 in your java code, with localhost not connect and throws this exception.

Orchidectomy answered 26/3, 2023 at 22:30 Comment(0)
T
0

I had to change my SQL setup (in my host, Dreamhost in my case) to allow the username to access the database from other hosts, not just Dreamhost since I'm running a program from the IDE on my computer. I did that for now by adding % to the list of Allowable Hosts. It now works!

Tourism answered 16/11, 2017 at 2:18 Comment(1)
I should add that this is similar to #munchkins approach but from the SQL control panel end.Tourism
S
0

The order of declaring:

  • Driver
  • Connection string
  • username
  • password

If we declaring in order

  • Connection string
  • username
  • password
  • Driver

the application will fail

Silicone answered 2/6, 2019 at 0:58 Comment(0)
A
0
  1. use correct jar (with correct version)
  2. give root user host-independent access or create a user
Audriaaudrie answered 30/12, 2019 at 19:31 Comment(0)
A
0

For me the solution worked as by changing the url format to: con=DriverManager.getConnection("jdbc:mysql://localhost/w3schools?user=###&password=###"); make sure to add proper jar to class path and use the driver Class.forName("com.mysql.jdbc.Driver");

Atombomb answered 13/3, 2020 at 18:23 Comment(0)
T
0

This resolved issue for me.

ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'password';

GRANT ALL PRIVILEGES ON *.cfe TO 'root'@'%' IDENTIFIED BY 'password';

FLUSH PRIVILEGES;
Tifanytiff answered 4/6, 2020 at 8:24 Comment(0)
L
0

I was also facing the same issue, My connection string is valid and username and password also valid, even user has sufficient privileges to access database.

I solved this issue by deleting temporary folder created by MySQL(Please take backup before deleting any folders so in case if it not works then you can place that files again).

Default folder location for temp and connection files of MySQL in Windows is:

C:\ProgramData\MySQL

I deleted(taken backup) of below folder:

C:\ProgramData\MySQL\MySQL Server \Data\sys

Note: Before deleting any items make sure that MySQL service is not started or else it would not allow to delete any files

And It works for me.

Lamellate answered 13/6, 2020 at 13:2 Comment(0)
A
0

It's working fine for me while using same password after executing the following statement:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'root';
Aloft answered 5/9, 2021 at 12:2 Comment(0)
A
0
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=create-drop
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=
spring.datasource.url=jdbc:mysql://localhost:3306/DATABASE_NAME? useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

Go to your phpmyadmin database

Create a database called DATABASE_NAME and go to priviledges and check the users who have priviledges in the database and use them the default is "root"

Astred answered 5/12, 2021 at 13:20 Comment(0)
H
0

Due to below reason I created new user and password for mysql, now I am able to connect successfully. if your password is in encoded format please create new password

https://www.digitalocean.com/community/tutorials/how-to-create-a-new-user-and-grant-permissions-in-mysql#:~:text=There%20is%20a,mysql_native_password%20plugin%20instead%3A

There is a known issue with some versions of PHP that causes problems with caching_sha2_password. If you plan to use this database with a PHP application — phpMyAdmin, for example — you may want to create a user that will authenticate with the older, though still secure, mysql_native_password plugin instead:

Handful answered 4/8, 2022 at 11:38 Comment(0)
M
0

Sometimes MySQL server, while creating the user, sets the authentication type other than 'Standard'. The user I was using had the authentication type set to 'caching_sha_password'. Because of this, the connection was failing.

I created a new user via MySQL Workbench with all the privileges and set the authentication type to 'Standard', and the exception was gone.

enter image description here

Miss answered 11/7, 2023 at 5:46 Comment(0)
C
0

Install mysql-server for developer from here: https://dev.mysql.com/downloads/file/?id=526407 and configure it according to your properties (username & password)

After you installed it, open the MySql app and configure it with username & password and db-name.

Cytochemistry answered 27/3 at 20:42 Comment(1)
I believe the OP has already downloaded MySQL and he has probably already configured it and I guess he configured it incorrectly otherwise he wouldn't be getting an error. So how does your answer help resolve the problem that is described in the posted question?Somatist
H
-1

I encountered this error. The problem was that I had the wrong database name.

Huguenot answered 18/12, 2017 at 3:42 Comment(0)
C
-1

If you are connecting a remote mysql server from your local machine using java see the below steps. Error : "java.sql.SQLException: Access denied for user 'xxxxx'@'101.123.163.141' (using password: YES) "

for remote access may be cpanel or others grant the remote access for your local ip address.

In the above error message: "101.123.163.141" is my local machine ip. So First we have to give remote access in the Cpanel-> Remote MySQL®. Then run your application to connect.

Class.forName("com.mysql.jdbc.Driver");  
Connection con=DriverManager.getConnection(  
    "jdbc:mysql://www.xyz.com/abc","def","ghi");  
//here abc is database name, def is username and ghi        
Statement stmt=con.createStatement();  
ResultSet rs=stmt.executeQuery("select * from employee");  
    while(rs.next())  
        System.out.println(rs.getInt(1)+" "+rs.getString(2)+"  
                          "+rs.getString(3));  
con.close();    

Hope it will resolve your issue.

Thanks

Commonly answered 18/11, 2018 at 16:32 Comment(0)
M
-1

I also have this problem, this solved it.

Change the:

Sring url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&user=root&password=password";

Set:

"serverTimezone=UTC" is "Unified standard world time". "useUnicode=true&characterEncoding=UTF-8" is "Solve Chinese garbled".

Although my database have not any Chinese words. But it is working. Reference from https://www.cnblogs.com/EasonJim/p/6906713.html

Meraree answered 16/9, 2019 at 7:23 Comment(1)
Please format your code and do not deliver a link to an external page here if possible. Sum up everything directly into your post. Thanks.Blackstock
E
-1

If you are using a MySql workbench, go to the home page of workbench, right click on your database, copy the JDBC connection string, and paste it into the Java program.

Escuage answered 3/1, 2020 at 18:4 Comment(0)
B
-2

be sure that the port you are using in:

spring.datasource.url=jdbc:mysql://localhost:8000/database

is the same that MySQL uses on your machine: check for it with this command in MySQL CLI:

SHOW VARIABLES WHERE Variable_name = 'port';
Bogan answered 6/7, 2022 at 4:48 Comment(2)
The OP (from 10 years ago, I suspect they've moved on by now) shows access denied and not some sort of failed connection. So the port number is not likely the problem, since they must have been able to connect in order to have the credentials rejected.Muse
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewHessite

© 2022 - 2024 — McMap. All rights reserved.