QGA*_*QGA 2 java mysql sql jdbc return-value
为什么你认为这个函数总是让我?使用另一个具有相同代码结构的登录程序,它可以很好地工作.我的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;
}
Run Code Online (Sandbox Code Playgroud)
Access表由三列组成:UserID,UserName,UserPassword
java.sql.SQLException:对用户'root'@'localhost'拒绝访问(使用密码:YES)
正如您所提到的,问题在于与数据库本身建立连接.声明
con = DriverManager.getConnection(DatabaseURL, userName, password);
Run Code Online (Sandbox Code Playgroud)
正在抛出被抓住的异常
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
之后您将返回dbresult已初始化的null(您必须将其作为局部变量).所以问题是由于身份验证,您无法连接到数据库.
在您的计算机上(在本例中为localhost)从控制台运行以下命令
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'root' WITH GRANT OPTION;
Run Code Online (Sandbox Code Playgroud)