我的数据库中有一个布尔字段,我想让用户检查该用户是管理员用户还是普通用户。该代码引人注目且运行良好,只是无法按预期工作
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
boolean aux = false;
String sql = "select * from UserInfo where username=? and password=? and Admin=?";
try {
pst = conn.prepareStatement(sql);
pst.setString(1, text_username.getText());
pst.setString(2, text_password.getText());
pst.setBoolean(3, aux);
if (aux == true) {
rs = pst.executeQuery();
if (rs.next()) {
rs.close();
pst.close();
close(); // to close this frame
AccessControl AC = new AccessControl();
AC.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "Username or Password are incorrect");
}
} else {
JOptionPane.showMessageDialog(null, "Access denied");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
} finally {
try {
rs.close();
pst.close();
} catch (Exception e) {
}
}
}
您的程序需要进行以下更改:
A。如下更改jButton1ActionPerformed
的签名:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt, boolean aux)
[接受aux
的值作为参数,或从某些输入字段(例如,复选框)中读取其值,这是您从文本字段中读取用户名和密码的方式。
如果使用第一个选项(即更改jButton1ActionPerformed
的签名以接受aux
的值作为参数),则在代码中,还需要将jButton1ActionPerformed(evt);
更改为jButton1ActionPerformed(evt,true);
或[ C0],具体取决于您的要求(即,如果用户为ADMIN,则为jButton1ActionPerformed(evt,false);
;如果不是ADMIN的用户,则为true
。
B。更改false
,如下所示:
sql
C。如下更改您的第一个String sql = "SELECT * FROM UserInfo WHERE username=? AND password=?"
块:
try...catch
首先,我想对您的重放表示感谢。我刚刚找到了一个很好的解决方案,它现在可以正常运行。这是:
try {
pst = conn.prepareStatement(sql);
pst.setString(1, text_username.getText());
pst.setString(2, text_password.getText());
if (aux == true) {
rs = pst.executeQuery();
if (rs.next()) {
rs.close();
pst.close();
close(); // to close this frame
AccessControl AC = new AccessControl();
AC.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "Username or Password are incorrect");
}
} else {
JOptionPane.showMessageDialog(null, "Access denied");
}
}
Les代码更新,现在没有任何错误:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
boolean aux = false;
String sql = "select * from UserInfo where username=? and password=?";
try{
pst=conn.prepareStatement(sql);
pst.setString(1, text_username.getText());
pst.setString(2, text_password.getText());
rs=pst.executeQuery();
aux=rs.getBoolean("Admin");
if (aux == true){
if(rs.next()){
rs.close();
pst.close();
close(); // to close this frame
AccessControl AC = new AccessControl();
AC.setVisible(true); }
else {
JOptionPane.showMessageDialog(null, "Username or Password are incorrect");
}
} else {
JOptionPane.showMessageDialog(null, "Access denied");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
} finally {
try {
rs.close();
pst.close();
} catch(Exception e) {
}
}
}