我的 java 代码中有 TestingID
变量和一个 sql 字符串,如下所示。 sql 字符串稍后将用于 prepareStatement
。
int TestingID;
String sqlInsert = "INSERT INTO TESTING VALUES(TESTING_SEQ.NEXTVAL, ?, ?)";
...
MethodA(TestingID); //passing TestingID to MethodA
我需要将新插入记录的下一个序列值获取到 TestingID
中,以便我可以在另一个方法中使用它,如上所示。
最佳答案
通过使用该方法,您应该首先查询新的标识值(我看到您正在使用序列)。这可以通过发出选择来完成。
// This example is for Oracle
String sqlIdentifier = "select TESTING_SEQ.NEXTVAL from dual";
PreparedStatement pst = conn.prepareStatement(sqlIdentifier);
synchronized( this ) {
ResultSet rs = pst.executeQuery();
if(rs.next())
long myId = rs.getLong(1);
之后,将其作为参数传递给 preparedStatement。
...
String sqlInsert = "INSERT INTO TESTING VALUES(?, ?, ?)";
PreparedStatement pst = conn.prepareStaetment(sqlInsert);
pst.setLong(1, myId);
...
从那时起,您将始终拥有自己的序列号。
这些不是功能示例(没有 catch 或 finally 等),但会让您了解如何做;)
关于java在插入前获取记录的SQL下一个序列号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18002377/