由于某种原因,此方法总是返回 false。我已经输入了正确的凭据并尝试但返回错误的调用者。请帮忙。
public Boolean validate(String username, String password) {
System.out.println(username);
System.out.println(password);
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/login?"+"user=Naveen&password=Naveen");
String sql = "select * from login.user where username=? and password=?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(0, username);
pst.setString(1, password);
ResultSet rs = pst.executeQuery();
if(rs.next()){
return true;
}else{
return false;
}
} catch (Exception e) {
return false;
}
}
最佳答案
PreparedStatement
的参数索引以 1
而非 0
开头。设置参数的正确方法是:
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, username);
pst.setString(2, password);
我还建议对 Closeable
资源(例如 Connection
或 PreparedStatement
)使用 try-with-resources block 。或者如果您使用的是 7 之前的 Java,至少在 finally block 中关闭它们。
关于java - 无法让登录应用程序工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36392077/