我正在尝试设置一个登录系统,当用户输入他的用户名和密码并按下登录按钮时,他的用户名和密码将在 SQL 语句中发送,以与数据库中的用户匹配。如果用户名和密码正确(如果它们在数据库中匹配),则使用数据库中的所有用户数据创建一个用户对象,并将用户带到管理仪表板
在对结果集等进行了大量研究并通过大量代码之后,我仍然无法使其在我的系统中运行。谁能告诉我这样做的好方法?或者告诉我这段代码是否有明显的问题?
当我输入用户名和密码并按登录时,我在控制台中收到错误:
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.OraclePreparedStatement.setStringInternal(OraclePreparedStatement.java:5321)
at oracle.jdbc.driver.OraclePreparedStatement.setString(OraclePreparedStatement.java:5309)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.setString(OraclePreparedStatementWrapper.java:280)
at database.UserOperations.validateLog(UserOperations.java:45)
at gui.Login$2.mouseClicked(Login.java:77)
一些gui代码
JButton btnLogin = new JButton("Login");
btnLogin.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
UserOperations userOperations = new UserOperations();
ResultSet rset = userOperations.validateLog(textFieldUsername.getText(), textFieldPassword.getText());
User user = null;
try {
if (rset.next()) {
user = new User(rset.getInt("userID"), rset.getString("userName"), rset.getString("userPassword"), rset.getString("securityQuestion"), rset.getString("securityAnswer"),
rset.getInt("adminRights"), rset.getString("email"), rset.getString("fName"), rset.getString("phoneNumber"), rset.getString("department"));
dispose();
AdminDashboard admin = new AdminDashboard();
admin.setVisible(true);
}
else{
JOptionPane.showMessageDialog(null, "Login fail!", "Error", JOptionPane.WARNING_MESSAGE);
}
} catch (SQLException e2) {
e2.printStackTrace();
}
}
});
验证登录()方法
public ResultSet validateLog(String username, String userpassword)
{
try {
String sql = "SELECT userid, username, userpassword, securityquestion, securityanswer, adminrights, email, fname, phonenumber, department FROM systeuser WHERE username = ? AND userpassword = ?";
stmt = conn.prepareStatement(sql);
stmt.setString (2, username);
stmt.setString (3, userpassword);
rset = stmt.executeQuery ( );
}
catch(Exception e){
e.printStackTrace ( );
JOptionPane.showMessageDialog (null, "Login Failed", null, JOptionPane.WARNING_MESSAGE);
}
return rset;
}