需要创建三个用户登录名,一旦登录,每个登录用户都需要具有不同的界面。我的操作按钮脚本如下:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://localhost:1433;databaseName=77OOP062;user=sa;password=hnd";
Connection conn= DriverManager.getConnection(url);
String sql ="Select Type from Users where Username=? and Password=?";
PreparedStatement pst =conn.prepareStatement(sql);
pst.setString(1, jTextFieldUserName.getText());
pst.setString(2, jTextFieldPassword.getText());
ResultSet rs = pst.executeQuery();
rs.next();
String name = rs.getString("Type");
if (name.equals("admin")) {
JOptionPane.showMessageDialog(null, "Access Permitted");
ManageUI ah = new ManageUI();
ah.setVisible(true);
}
if (name.equals("cashier")){
JOptionPane.showMessageDialog(null, "Access Permitted");
CashierUI eh = new CashierUI();
eh.setVisible(true);
}
else if (name.equals("stockkeeper")){
JOptionPane.showMessageDialog(null, "Access Permitted");
StockKeeperUI aq = new StockKeeperUI();
aq.setVisible(true);
}
conn.close();
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
This is my Sql server database: User
-----------------------------------------------
Username | Type | Password |
-----------------------------------------------
mick | admin | 123 |
-----------------------------------------------
nisha | cashier | 456 |
-----------------------------------------------
sam | stockkeeper | 789 |
-----------------------------------------------
最佳答案
您忘记了以下代码中最后一个没有匹配的内容时的处理方法(如果包含else则在第二个代码中第二个),以完成if else链。
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://localhost:1433;databaseName=77OOP062;user=sa;password=hnd";
Connection conn= DriverManager.getConnection(url);
String sql ="Select Type from Users where Username=? and Password=?";
PreparedStatement pst =conn.prepareStatement(sql);
pst.setString(1, jTextFieldUserName.getText());
pst.setString(2, jTextFieldPassword.getText());
ResultSet rs = pst.executeQuery();
if(rs.next()){ // Row Exists
String name = rs.getString("Type");
if (name.equals("admin")) {
JOptionPane.showMessageDialog(null, "Access Permitted");
ManageUI ah = new ManageUI();
ah.setVisible(true);
}
else if (name.equals("cashier")){
JOptionPane.showMessageDialog(null, "Access Permitted");
CashierUI eh = new CashierUI();
eh.setVisible(true);
}
else if (name.equals("stockkeeper")){
JOptionPane.showMessageDialog(null, "Access Permitted");
StockKeeperUI aq = new StockKeeperUI();
aq.setVisible(true);
}else {
JOptionPane.showMessageDialog(null, "Access Denied");
}
} else{
JOptionPane.showMessageDialog(null, "Access Denied"); // Row Doesnot exists
}
conn.close();
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
关于java - Java(Netbeans)-如何在if语句中为“访问被拒绝”编码,我尽力了但它没有用..?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46334940/