首页 > 解决方案 > 如何在组合框中显示值并将其 id 保存到数据库中

问题描述

我有一个显示值而不是 Id 的组合框。然后应该将 id 插入数据库。我向组合框添加了一个侦听器以获取 ID。通过 sysout 我可以看到,但我怎么能插入数据库????

这是代码:

public void comboboxpersonneldata() {
    comboboxpersonnellist = FXCollections.observableArrayList();
    handler = new DBHandler();
    connection = handler.getConnection();
    try {
        rs = connection.createStatement().executeQuery("SELECT num_personnel,nom_personnel FROM personnel");
        while (rs.next()) {
            // comboboxpersonnellist.add(rs.getInt(1));
            comboboxpersonnellist.addAll(new comboboxPersonnel(rs.getInt(1), rs.getString(2)));
        }
        combopersonnel.setItems(comboboxpersonnellist);
        combopersonnel.valueProperty().addListener((obs, oldval, newval) -> {
            if (newval != null) {
                System.out.println(newval.getNum_personnel());
            }
        });

    } catch (SQLException e) {
        e.printStackTrace();
    }
    try {
        rs.close();
        connection.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

和模型类:

public class comboboxPersonnel {
    int num_personnel;
    String name_personnel;

    public comboboxPersonnel(int num_personnel, String name_personnel) {
        this.num_personnel = num_personnel;
        this.name_personnel = name_personnel;
    }

    public int getNum_personnel() {
        return num_personnel;
    }

    public String getName_personnel() {
        return name_personnel;
    }

     @Override
     public String toString() {
         return name_personnel;
     }

}

标签: javajavafx

解决方案


推荐阅读