Javafx: добавить новую строку в табличное представление и обновить базу данных - PullRequest
0 голосов
/ 25 апреля 2020

Мой сценарий: у меня есть всплывающая сцена с кнопкой «Добавить запись», которая добавляет новую редактируемую строку в таблицу на том же этапе. Когда пользователь вводит данные в любой столбец, он должен обновить их до базы данных. Я использовал пример в этом вопросе и немного его изменил.

@FXML
private TableView<Student> table;

@FXML
private TableColumn<Student, LocalDate> dateColumn;

@Override
public void initialize(URL url, ResourceBundle rb) {


    Callback<TableColumn<Student, LocalDate>, TableCell<Student, LocalDate>> cellFactory = 
            (TableColumn<Student, LocalDate> param) -> new DatePickerCell(); // the DatePickerCell is a different class to ovveride TableCell. 
    dateColumn.setCellValueFactory(cellData -> cellData.getValue().dateProperty());
    dateColumn.setCellFactory(cellFactory);

    table.setEditable(true);        

    dateColumn.setOnEditCommit(event -> {
        Student user = event.getRowValue();
        user.setWeekDate(event.getNewValue());
        //Date is the name of the column that will be passed for the SQL statement, 
        //getID is to get the id of the inserted row in the database so that the data can be updated. the id is an auto incremented value
        updateDate("Date", event.getNewValue(), user.getID());
    });     
}

updateDate: # этот код должен обновить столбец даты в базе данных

private void updateDate(String column, LocalDate date, int id) {
        Connection c;
        try {
            c = DbConnect.getInstance().getConnection();
            PreparedStatement stmt = c.prepareStatement("UPDATE tableName SET "+column+" = ? WHERE ID = ? ");

            stmt.setDate(1, java.sql.Date.valueOf(date));
            stmt.setInt(2, id);
            stmt.executeUpdate();
        } catch (SQLException ex) {
            System.err.println("Error");
            // if anything goes wrong, you will need the stack trace:
            ex.printStackTrace(System.err);
        }
    }

Это код кнопки «Добавить», при нажатии которого он добавляет строку в таблицу, готовую для ввода данных в каждый столбец:

public void addRow() {
// get current position
    TablePosition pos = table.getFocusModel().getFocusedCell();

    // clear current selection
    table.getSelectionModel().clearSelection();

    // create new record and add it to the model
    Student data = new Student();
    table.getItems().add(data);
    // get last row
    int row = table.getItems().size() - 1;
    table.getSelectionModel().select( row, pos.getTableColumn());

    // scroll to new row
    table.scrollTo( data);

    added = true;
    }

проблема заключается в том, что когда я вставляю новую строку и фиксирую изменения в tableview это не вставляет это в базу данных. Я также попытался использовать SQL INSERT вместо UPDATE, но проблема все еще та же.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...