0

I am trying to connect to MySQL database and fetch some data using sql statement in my java code. but i cant connect to my database with the following SQL Exception.

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

my java code is as bellow:

Mysql_connecter.java

package mysql_connecter;

import java.sql.*;
/**
 *
 * @author kass
 */
public class Mysql_connecter 
{
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("connecting.....");
            try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password")) 
            {
                System.out.println("connected to mysql DB");
                Statement stmt=con.createStatement();

                ResultSet rs=stmt.executeQuery("select * from my_table");

                while(rs.next())
                {
                    System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));
                }
            }
            catch(SQLException e)
            { 
                System.out.println("ERROR: ["+e+"]");
            }
        }
        catch(ClassNotFoundException e)
        { 
            System.out.println(e);
        }
    } 
}

i have added the mysql jdbc driver to my library path. can some one point me i miss something in my code?

  • Please try to access to the database using a MysqlClient like PHPMyAdmin or Heidisql. If you cannot access with a client - you cannot expect that it works with java. – baumfreund Mar 29 '19 at 08:20

2 Answers2

0

seems you have no password set for your user. Go to mysql database and check user table to confirm the username and password for the user.

corroborator
  • 321
  • 2
  • 11
0

It might be an issue with using Username+Password combination but not having native authentication enabled on database side.

Are you able to change the password of the user using this command:

ALTER USER 'jeffrey'@'localhost'
IDENTIFIED WITH mysql_native_password
BY 'password';

https://dev.mysql.com/doc/refman/8.0/en/alter-user.html

For more information on how native authentication works see

MySQL 8.0 Reference for Native Pluggable Authentication

or if you are using MySQL 5.7 see MySQL 5.7 Reference for Native Pluggable Authentication

Florian Schlag
  • 639
  • 4
  • 16