简体   繁体   中英

Check existing entry in database + auto increment id -> multiple conditions

I'm creating a GUI application with an user form to generate a sheet, those sheets are saved in the H2 database, as for the user form I enter manually the sheet number in a textfield and the date from a datepicker.

Every sheet has its ID which shall be unique for that month. The first created sheet for that month has id 1, and 2nd is 2 and so on but for the next month the ID should restart from 1.

I need to check if the entry already exists in the database with that sheet number in that month. I created another column in the database where the number+month+year I extract from the textfields are stored and I check it there, but I am looking for another method without having to create the extra column.

Here are the setter and getters (I pasted only the 3 values):

public class FiseDetails {

    private final IntegerProperty sheetNumber;
    private final ObjectProperty<Date> sheetDate;
    private final StringProperty numberAndDate;

public FiseDetails(Integer sheetNumber, Date sheetDate, String numberAndDate) {
        this.sheetNumber = new SimpleIntegerProperty(sheetNumber);
        this.sheetDate = new SimpleObjectProperty<>(sheetDate);
        this.numberAndDate = new SimpleStringProperty(numberAndDate);
}

    public Integer getSheetNumber() {
        return sheetNumber.get();
    }

    public void setSheetNumber(Integer value) {
        sheetNumber.set(value);
    }

    public IntegerProperty SheetNumberProperty() {
        return sheetNumber;
    }

    public Date getSheetDate() {
        return sheetDate.get();
    }

    public void setSheetDate(Date value) {
        sheetDate.set(value);
    }

    public ObjectProperty SheetDateProperty() {
        return sheetDate;
    }

    public String getNumberAndDate() {
        return numberAndDate.get();
    }

    public void setNumberAndDate(String value) {
        numberAndDate.set(value);
    }

    public StringProperty NumberAndDateProperty() {
        return numberAndDate;
    }

}

Here is part of the controller:

public class StartGUIController implements Initializable {

    Connection conn = DbConnection.Connect();
    ObservableList<FiseDetails> data = FXCollections.observableArrayList();
    PreparedStatement preparedStatement = null;
    ResultSet rs = null;

    @FXML
    private TextField txt_SheetNumber;

    @FXML
    private DatePicker sheetDate;

@FXML
    void generateSheet(ActionEvent event) throws SQLException {

        Integer id = Integer.parseInt(txt_SheetNumber.getText());
        LocalDate selectedDate = sheetDate.getValue();
        Date date = Date.valueOf(selectedDate);
        LocalDate strgDate = sheetDate.getValue();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM- yyyy");
        String formatedDate = (strgDate).format(formatter);
        String last7 = formatedDate.substring(formatedDate.length() - 7);
        String numberAndDate = txt_SheetNumber.getText() + " " + last7;

try (PreparedStatement checkNumberAndDateExists = conn.prepareStatement("SELECT 1 FROM SHEETSDB WHERE NUMBERANDDATE = ?")) {
            checkNumberAndDateExists.setString(1, numberAndDate);
            try (ResultSet result = checkNumberAndDateExists.executeQuery()) {
                if (result.next()) {
                    Alert confirmation = new Alert(AlertType.INFORMATION);
                    confirmation.setTitle("Fisa existenta");
                    confirmation.setHeaderText(null);
                    confirmation.setContentText("Fisa " + txt_SheetNumber.getText() + "/" + sheetDate.getValue() + " exista");
                    confirmation.showAndWait();

                } else {
                    String query = "INSERT INTO SHEETSDB (ID, SHEETDATE,  NUMBERANDDATE) VALUES (?,?,?)";
                    preparedStatement = null;
                    try {
                        preparedStatement = conn.prepareStatement(query);
                        preparedStatement.setInt(1, id);
                        preparedStatement.setDate(2, date);
                        preparedStatement.setString(26, numberAndDate);

                    } catch (SQLException e) {
                        System.out.println(e);
                    } finally {
                        preparedStatement.execute();
                        preparedStatement.close();
                    }

                    Alert confirmation = new Alert(AlertType.INFORMATION);
                    confirmation.setTitle("Finalizare generare fisa");
                    confirmation.setHeaderText(null);
                    confirmation.setContentText("Fisa " + txt_SheetNumber.getText() + "/" + sheetDate.getValue() + " a fost creata cu succes");
                    confirmation.showAndWait();
                    TableData();
                }
            }
        }

    }

@Override
    public void initialize(URL url, ResourceBundle rb) {
//here I have some code that does not have any impact on my problem
     }
  1. My question is how can I efficiently check if the sheet number already exists in the database for that month without having to create the extra column. Let me know if you think that the actual solution is the best one, as the extra column is the only column that is unique, so that's the column I also use when I need to remove a row from the database.

  2. Also I can't think of a solution to auto increment the sheet number and set it to the textfield, like check the last sheet number from current month and set it to the "txt_SheetNumber" textfield, if none set it to 1, so whenever I initialize the app to have already the sheet number in the textfield. If you can help me with that also would be much appreciated.

This is my first time working with Java or any other programming language, so feel free to comment on any aspect. The application is for me only to make my work easier.

After some digging, I found a solution for the 2nd problem. Let me know if I shall improve it.

int lastId() {

    int newSheetNumber=0;
    String query = "SELECT MAX(ID) FROM SHEETSDB WHERE MONTH(`SHEETDATE`)=MONTH(NOW()) AND YEAR(`SHEETDATE`)=YEAR(NOW())";
    try {
        preparedStatement = conn.prepareStatement(query);

        rs = preparedStatement.executeQuery();
        if (!rs.next()) {
            newSheetNumber = 1;
        }else {
            newSheetNumber = rs.getInt(1) + 1;
        }
        preparedStatement.close();
        rs.close();
        //System.out.println("The new sheet is: " + newSheetNumber);
    } catch (SQLException ex) {
        System.err.println("Error " + ex);
    }
    return newSheetNumber;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM