我试过的:

try
    {
        PreparedStatement pstat = con.prepareStatement("insert into student_info values (?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
        pstat.setInt(1, Integer.parseInt(txtId.getText()));
        pstat.setString(2, txtFName.getText());
        pstat.setString(3, txtLName.getText());
        pstat.setString(4, gender);
        int result = pstat.executeUpdate();

        if(result > 0)
        {
            JOptionPane.showMessageDialog(null,"Data Inserted Succesfully !!!");
            txtId.setText("");
            txtFName.setText("");
            txtLName.setText("");
            bg.clearSelection();
            ResultSet rs = pstat.getGeneratedKeys();
            int newId= -1;
            if(rs != null && rs.next())
            {
                newId = rs.getInt(1);
                txtId.setText(String.valueOf(newId));
            }
        }
    }

我想要的:
要在文本框中显示的新id
不会发生的事情:
新的id不会显示在textfield中。。

最佳答案

对代码进行以下更改:

PreparedStatement pstat = con
    .prepareStatement("insert into student_info (firstname,lastname,gender)
        values (?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS); // omit id column
pstat.setString(1, txtFName.getText());
pstat.setString(2, txtLName.getText());
pstat.setString(3, gender);
int result = pstat.executeUpdate();
// now got fetch the generated id

10-04 22:42