如果从JavaFX中的ResultSet中找不到任何内容,则显示警报

时间:2016-12-06 12:35:06

标签: java mysql javafx

此代码用于在单击按钮后显示错误。 buttonclick所做的是检查用户名和密码是否与数据库中的用户名和密码相对应。

如果为true,它将显示下一个场景。如果错,我想表明我犯的错误。显示下一个场景工作正常,显示错误没有。

这是我的代码:

public Pane createLogin() throws SQLException {
    GridPane gridPane = new GridPane();
    gridPane.setHgap(10);
    gridPane.setVgap(10);
    gridPane.setPadding(new Insets(20, 150, 10, 10));

    Button login = new Button("Login!");
    TextField usernameField = new TextField();
    usernameField.setPromptText("Username");
    PasswordField passwordField = new PasswordField();
    passwordField.setPromptText("Password");
    Alert alert = new Alert(Alert.AlertType.ERROR);
    alert.setTitle("ERROR");
    alert.setHeaderText("OH SNAP");
    alert.setContentText("I have a great message for you!");

    login.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {

            String username = usernameField.getText();
            String password = passwordField.getText();
            String query = "Select * from user WHERE username ='" + username + "' and password ='" + password + "'";
            ResultSet rs = null;
            System.out.println("hahah:" + username);
            try {
                rs = dataBase.executeQuery(query);
                dataBase.executeDataRowQuery(query);
                while (rs.next()) {
                    if (username.equals(rs.getString("username"))) {
                        if (password.equals(rs.getString("password"))) {
                            switchScreen(createOverview());
                        } else{
                            alert.showAndWait();
                        }
                    } else{
                        alert.showAndWait();
                    }
                    alert.showAndWait();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }


        }
    });
    gridPane.add(new Label("Username: "), 0, 0);
    gridPane.add(usernameField, 0, 1);
    gridPane.add(new Label("Password: "), 1, 0);
    gridPane.add(passwordField, 1, 1);

    gridPane.add(new Label("Login!"), 2, 0);
    gridPane.add(login, 2, 1);

    return gridPane;
}

1 个答案:

答案 0 :(得分:1)

如果ResultSet.next返回,如果存在更多行,则可以执行

if (rs.next()) {
    switchScreen(createOverview());
} else {
    alert.showAndWait();
}

或者使用SELECT COUNT(*) FROM ...并检查第一行中的第一列:

if (rs.next() && rs.getInt(1) > 0)
    ...

注意:我不会详细说明SQL注入或其他严重的安全问题,例如允许读取密码和用户名信息......