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

为什么你认为这个函数总是让我? 使用另一个具有相同代码结构的登录程序,它可以很好地工作。 我的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; } 

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

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

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

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

抛出被抓住的exception

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

之后您将返回已初始化为null dbresult (您必须将其作为局部变量)。 所以问题是由于身份validation,您无法连接到您的数据库。

在您的计算机上(在本例中为localhost)从控制台运行以下命令

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