我有一个连接到数据库后端的小型 Java 项目。我有一个登录功能,但是当我把它放在我的测试线束中时,我无法让它给我正确的输出。
public boolean validateLogin(User validate) {
{
Connection conn = null;
String dbUserName = "root"; // MySQL database username
String dbPassword = "nbuser"; // MySQL database password
boolean returnValue = false;
String dbUrl = "jdbc:mysql://localhost:3306/project";
try {
Class forNam = Class.forName("com.mysql.jdbc.Driver");
try {
forNam.newInstance();
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
}
} catch (ClassNotFoundException ex) {
}
try {
conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
System.out.println("Database connection establish...!");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM login_register WHERE user_id='" + validate.getUserID() + "'");
if (rs.next()) {
if (rs.getString(2).equals(validate.getUserPassword())) {
System.out.println("User and Password Match");
} else {
System.out.println("No User Or Password Match");
}
}
else {
System.out.println("No User Or Password Match");
}
} catch (SQLException ex) {
System.out.println("Cannot connect to database server...!!");
} finally {
if (conn != null) {
try {
conn.close();
System.out.println("Database connection terminated...!!!");
returnValue = true;
} catch (SQLException ex) {
}
}
}
return returnValue;
}
}
现在我的测试代码看看这个语句是否有效
User testLogin = new User();
testLogin.setUserID("userid");
testLogin.setUserPassword("password");
if (test.validateLogin(testLogin)) {
System.out.println("User logged in");
}
else {
System.out.println("Failed to login");
}
上面的两位信息都在我的数据库中,所以我在 IDE 中的输出如下:
Database connection establish...!
User and Password Match
Database connection terminated...!!!
User logged in
但是如果我将值更改为不在数据库中的值,我会得到
Database connection establish...!
No User Or Password Match
Database connection terminated...!!!
User logged in
所以问题出在我的测试代码中,当值不匹配时,我无法说它们不匹配,我稍后在工作中需要一个函数。任何想法我需要在我的测试代码上进行更改才能说出"failed to login"
我的测试端的 id 和密码是否不匹配