我想从Java组合框选择的项目中保存键,我做了此功能,因此我可以返回表“国籍”的入门键并将其作为外键插入其他表中,但它不起作用,它总是返回0:
public int getNat() throws Exception{
String query = "SELECT code_nat FROM nationality WHERE nationality=?";
try ( PreparedStatement stat = cnx.prepareStatement(query) ) {
stat.setString(1, (String)cmbNat.getSelectedItem());
rslt = stat.executeQuery();
return rslt.getInt(1);
}catch(SQLException ex){
ex.printStackTrace();
return 0;
}
}
最佳答案
您不能选择表的所有字段:
String query = "SELECT * FROM nationality WHERE nationality=?";
// ↑ here
请改用字段名:
String query = "SELECT nationality_id FROM nationality WHERE nationality=?";
也对retrieve data check here来说,但这必须起作用
return rs.getInt("nationality_id");