首页 > 解决方案 > 从数据库中获取组合框值

问题描述

我想ComboBox从数据库中获取值。我正在尝试以下代码,它不会返回任何错误,但不会返回添加到 ComboBox 的项目。

@FXML
private ComboBox<List> laptopos_combo;
public void filloscombo() throws SQLException
{
    String connectionUrl = "jdbc:sqlserver://WIN\\SQLEXPRESS:1433;database=itinventory;" + 
    "user=sa;"+ "password=Varpal@1234;";
    Connection connect= DriverManager.getConnection(connectionUrl);
    String query = "Select * from operatingsystem";
    
    PreparedStatement pst = connect.prepareStatement(query);
    // log.conn().prepareStatement(query);
    ResultSet os = pst.executeQuery();
    
    while(os.next())
    {
        ((List<String>) laptopos_combo).add(os.getString("os"));
    }
}

标签: javasqlsql-serverjavafxjdbc

解决方案


我认为您需要将 ComboBox 的项目类型从 List 更改为 String,因为您想向 ComboBox 添加一个字符串值,请尝试以下操作:

@FXML
private ComboBox<String> laptopos_combo;
public void filloscombo() throws SQLException {
    String connectionUrl ="jdbc:sqlserver://WIN\\SQLEXPRESS:1433;database=itinventory;" +
            "user=sa;"+ "password=Varpal@1234;";
    Connection connect= DriverManager.getConnection(connectionUrl);
    String query="Select * from operatingsystem";

    PreparedStatement pst = connect.prepareStatement(query);
    ResultSet os = pst.executeQuery();
    laptopos_combo.getItems().clear(); // Add this line to remove all items before you add the database one
    while(os.next()) {
        laptopos_combo.getItems().add(os.getString("os"));
    }
}

推荐阅读