java.sql.SQLException:拒绝用户“root”@“localhost”的访问(使用密码:YES)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22508922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:09:21  来源:igfitidea点击:

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

javamysqlsqljdbcreturn-value

提问by QGA

Why do you think this function gives me always null?? Using another login program, which has the same code structure, it works greatly. My DBURL is jdbc:mysql://localhost:8889/database

为什么你认为这个函数给我总是空?使用另一个具有相同代码结构的登录程序,效果很好。我的 DBURL 是 jdbc:mysql://localhost:8889/database

    public String retrieveUserPassword(String userName, String password) {

    String query = "SELECT UserPassword FROM Access where UserName='"+userName+"'";
    String dbresult=null; //this might be the problem, but I must define it

    try {
      Class.forName("com.mysql.jdbc.Driver");

    }catch (ClassNotFoundException ex1) {

      System.out.println("Driver could not be loaded: " + ex1);
      Logger.getLogger(DatabaseModel.class.getName()).log(Level.SEVERE, null, ex1);
    }
    try {

          //These are private variables declared at the top of the class 
          //and used by various functions   
          con = DriverManager.getConnection(DatabaseURL, userName, password);   
          st = con.createStatement(); 
          rs = st.executeQuery(query);

            if(rs.next()){

                dbresult= rs.getString(3);
            }

     }catch (SQLException e) {

      e.printStackTrace();
     }    

  return dbresult;

}

The Access table is composed of three columns: UserID, UserName, UserPassword

Access表由三列组成:UserID、UserName、UserPassword

采纳答案by Aniket Thakur

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

java.sql.SQLException:拒绝用户“root”@“localhost”的访问(使用密码:YES)

As you have mentioned problem is with creating connection with the database itself. Statement

正如您所提到的,问题在于与数据库本身建立连接。陈述

con = DriverManager.getConnection(DatabaseURL, userName, password);

is throwing exception which is getting caught at

正在抛出被捕获的异常

catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   

after which you are returning dbresultwhich you have initialized to null(which you have to as it is a local variable). So the problem is that you are unable to connect to your db due to authentication.

之后,您将返回dbresult已初始化的null(您必须这样做,因为它是一个局部变量)。所以问题是由于身份验证,您无法连接到您的数据库。

On your machine where (localhost in ur case ) run the following command from console

在您的机器上(在您的情况下为 localhost )从控制台运行以下命令

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