gpt4 book ai didi

java - 如何从mysql在java文本字段中自动生成id

转载 作者:行者123 更新时间:2023-11-29 05:17:41 25 4
gpt4 key购买 nike

我尝试过的:

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 没有显示在文本字段中..

最佳答案

对您的代码进行以下更改:

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

关于java - 如何从mysql在java文本字段中自动生成id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30473323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com