I want to save the key from a java combobox selected item i made this function so i could return the primery key of table "nationality" and insert it as foreign key in other tables but it doesn't work it return always 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;
}
}
you cannot select all fields of the table:
String query = "SELECT * FROM nationality WHERE nationality=?";
// ↑ here
Use the field name instead:
String query = "SELECT nationality_id FROM nationality WHERE nationality=?";
Also to retrieve data check here but this must work
return rs.getInt("nationality_id");
the insertion function
public void insertInfo() throws Exception{
try{
int codeNat = getNat();
String query = "INSERT INTO info (id,name,code_nat) VALUES (?,?,?)";
stat = cnx.prepareStatement(query);
stat.setString(1, txtId.getText());
stat.setString(2, txtName.getText());
stat.setInt(3, codeNat);
stat.execute();
Update_table();
}catch(SQLException ex){
JOptionPane.showMessageDialog(null,ex);
}
finally{
try{
stat.close();
cnx.close();
}catch(Exception e){
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.