如何查询数据到JFXComboBox

How to query data into JFXComboBox

我一直在尝试从我的数据库中查询数据并将其作为值

通过我的 JFXComboBox 传递

我尝试将它包装到 while loop 并将每个项目添加到 JFXComboBox 但它仍然没有显示我的数据的价值。

@FXML
JFXComboBox<String> combobox;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
  String sql = "Select * from transaction_type from transactions";
  try(Connection conn = SQLConnection.getConnection(); /*Singleton Class DB       Connection*/
  Statement statement = conn.createStatement();
  ResultSet rs = statement.executeQuery(sql))
 {
   while(rs.next()){
     combobox.getItems.add(rs.getString(2));
   }
 }
catch(SQLException e)
 {
   serr(e.getNessage());
 }
}

我希望 JFXComboBox 中的项目是在交易中找到的值

它不会执行查询它会由于语法错误而导致错误并抛出异常

String sql = "Select * from transaction_type from transactions";

此查询简化了从交易中获取所有记录的过程

//try this query
String sql = "Select * from transactions";

The correct way is to create a model class, however, I think this can help you.

创建方法:

public static void fillListFromDataBase (Connection conn, ObservableList<String> list) {
    String sql = "SELECT fieldName FROM transactions";
    try {
        Statement statement = conn.createStatement();
        ResultSet rs = statement.executeQuery(sql))

        while(rs.next()) {
            list.add(rs.getString("fieldName"));
        }
    } catch(SQLException e) {
        e.printStackTrace();
    }
}

然后调用方法加载列表中的数据并将列表绑定到Combobox:

JFXComboBox<String> combobox;

private ObservableList<String> list = FXCollections.observableArrayList();

@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
    Connection conn = SQLConnection.getConnection();

    fillListFromDataBase (conn, list);
    combobox.setItems(list);
}