我有這種方法,填補了我的組合框:從組合框中選擇項目時,如何從數據庫獲取ID值?
public DefaultComboBoxModel llenarComboFamilia() throws SQLException {
String query = "select * from familias";
DefaultComboBoxModel df = new DefaultComboBoxModel();
abrirConexion();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
//df.addElement(rs.getObject("This is the ID I need"));
df.addElement(rs.getString("String from DB"));
}
cerrarConexion();
return df;
}
然後,我加載它:
jComboBox2.setModel(con.llenarComboFamilia());
當我點擊「註冊」按鈕,我有:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
Persona p = new Persona(jTextField7.getText(), 1,
jComboBox2.getSelectedIndex() + 1,
jTextField5.getText(), jTextField6.getText());
con.insertarPersonasProp(p);
}
但jComboBox2.getSelectedIndex() + 1
不適合我,因爲我需要數據庫中的ID值,而不是選定的索引。
任何想法?