我有一个小应用程序。使用这个应用程序,我可以将新的员工记录添加到 MySQL 数据库,然后显示这些记录。buildData()
从数据库中检索数据并将其显示在 TableView 中,每次添加新记录以“刷新”TableView 时,我也会调用此方法。然而,这并不像预期的那样表现。
这是添加第一条记录后的视图:
当我点击按钮添加另一条记录时,这就是我得到的:
如果我关闭应用程序并重新打开它,TableView 是正常的:
这就是buildData()
方法的样子(方法忽略了类型检查和所有这些。可能是原因?)
private ObservableList<ObservableList> data;
public void buildData() {
Connection c;
TableColumn col;
data = FXCollections.observableArrayList();
try {
c = DataBaseConnection.connectToDatabase();
String SQL = "SELECT * FROM employees";
ResultSet rs = c.createStatement().executeQuery(SQL);
for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
final int j = i;
col = new TableColumn(rs.getMetaData().getColumnName(i + 1));
col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
employeeTableView.getColumns().addAll(col);
}
while (rs.next()) {
ObservableList<String> row = FXCollections.observableArrayList();
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
row.add(rs.getString(i));
}
data.add(row);
}
employeeTableView.setItems(data);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
然后是向数据库添加新员工记录的方法:
public void addEmployeeToDatabase() {
Employee employee = new Employee("Anne Droid", "Marketing", "Gender");
String query = "INSERT INTO employees (Employee_Name, Department, Gender) VALUES (?, ? , ?)";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, employee.getEmployeeName());
preparedStatement.setString(2, employee.getDepartment());
preparedStatement.setString(3, employee.getGender());
preparedStatement.execute();
buildData();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
最后是 Employee 类:
public class Employee {
private StringProperty employeeName;
private StringProperty department;
private StringProperty gender;
public Employee() {
}
public Employee(String employeeName, String department, String gender) {
this.employeeName = new SimpleStringProperty(employeeName);
this.department = new SimpleStringProperty(department);
this.gender = new SimpleStringProperty(gender);
}
public String getEmployeeName() {
return employeeName.get();
}
public StringProperty employeeNameProperty() {
return employeeName;
}
...
我正在使用纯 java,没有 FXML。我已经搜索过解决方案,但没有可用的解决方案(据我所知)。任何指针?