gpt4 book ai didi

Java/MySQL - 从最后保存的记录中检索 ID

转载 作者:行者123 更新时间:2023-11-29 19:03:04 25 4
gpt4 key购买 nike

有人可以帮我吗?我试图在创建记录时检索 ID(主键)并将其设置为文本字段。目前,它始终返回 1。我当前的方法如下:

connection = Utilities.getConnection();
String sqlQuery = "INSERT INTO student_details (Name, Surname, Date_Of_Birth, Gender, Address, Post_Code, Mobile_Number)" + " VALUES (?, ?, ?, ?, ?, ?, ?)";
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setString(1, txtFirstName.getText().trim());
preparedStatement.setString(2, txtSurname.getText().trim());
preparedStatement.setString(3, String.valueOf(dpDateOfBirth.getValue()));
preparedStatement.setString(4, cbGender.getSelectionModel().getSelectedItem().toString());
preparedStatement.setString(5, txtAddress.getText().trim());
preparedStatement.setString(6, txtPostCode.getText().trim());
preparedStatement.setString(7, txtMobileNo.getText().trim());
preparedStatement.executeUpdate();
txtStudentID.setText(String.valueOf(preparedStatement.RETURN_GENERATED_KEYS));
Utilities.showInforMsg("Record Saved:", "Record has been saved.");

最佳答案

您应该通过以下方式获取生成的 key :

ResultSet rs = preparedStatement.getGeneratedKeys();

if (rs.next()) {
key = rs.getLong(1);
}

你用这条线做什么

txtStudentID.setText(String.valueOf(preparedStatement.RETURN_GENERATED_KEYS));

正在将学生id设置为Statement接口(interface)的常量值(参见此处https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#RETURN_GENERATED_KEYS)

关于Java/MySQL - 从最后保存的记录中检索 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43712129/

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