有人可以帮帮我吗?我正在尝试在创建记录时检索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.");
答案 0 :(得分:0)
您应该通过以下方式获取生成的密钥:
ResultSet rs = preparedStatement.getGeneratedKeys();
if (rs.next()) {
key = rs.getLong(1);
}
你正在用这条线做什么
txtStudentID.setText(String.valueOf(preparedStatement.RETURN_GENERATED_KEYS));
将学生ID设置为Statement接口常量的值(请参阅此处https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#RETURN_GENERATED_KEYS)