9

I have TestingID variable and a sql string as follows in my java code. the sql string will later be used for prepareStatement.

 int TestingID; 

 String sqlInsert = "INSERT INTO TESTING VALUES(TESTING_SEQ.NEXTVAL, ?, ?)";  
 ...  

 MethodA(TestingID);     //passing TestingID to MethodA

I need to get the next sequence value of the newly inserted record into the TestingID so that I can use it in another method as shown above.

4

4 回答 4

32

By using that approach, you should query first for the new identity value (I see you're using sequences),. This can be done by issuing a select.

// 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);

After that, pass it to the preparedStatement as an argument.

...
String sqlInsert = "INSERT INTO TESTING VALUES(?, ?, ?)";
PreparedStatement pst = conn.prepareStaetment(sqlInsert);
pst.setLong(1, myId);
...

From that point, you will always have your sequence number.

These are not functional examples (no catch or finally, etc), but will give you an idea of how to do it ;)

于 2013-08-01T19:09:35.490 回答
4

In spring and Oracle database, this should work.

public Long getSequence() {
  org.springframework.jdbc.core.JdbcTemplate jdbcTemplateObject = new JdbcTemplate(dataSource);
  Long seq;
  String sql = "select SEQ_XY.NEXTVAL from dual";
  seq = jdbcTemplateObject.queryForObject(sql, new Object[] {}, Long.class);
  return seq;
}
于 2018-04-05T15:42:29.237 回答
0

In Oracle you can use

long myId = rs.getLong("NEXTVAL");

This will fail for HSQL. You can modify the sql statement, by adding "as NEXTVAL".

String sqlIdentifier = "select TESTING_SEQ.NEXTVAL as NEXTVAL from dual";
于 2014-01-21T16:40:34.373 回答
0

follow the below steps:

                 1) create sequence in database by using the following query.
CREATE SEQUENCE sequence_name
[START WITH start_num]
[INCREMENT BY increment_num]
[ { MAXVALUE maximum_num | NOMAXVALUE } ]
[ { MINVALUE minimum_num | NOMINVALUE } ]
[ { CYCLE | NOCYCLE } ]
[ { CACHE cache_num | NOCACHE } ]
[ { ORDER | NOORDER } ];

example:

CREATE SEQUENCE customers_seq
 START WITH     1000
 INCREMENT BY   1
 NOCACHE
 NOCYCLE;

2) check whether the sequence is created successfully. by executing command:

                       select * from user_sequences;

check for the name "customers_seq"

3) run the query:

sample program:

Statement stmt= connection.createStatement();

ResultSet rs = stmt.executeQuery("SELECT customers_seq.NEXTVAL FROM dual");

if ( rs!=null && rs.next() ) {
 int cust_id = rs.getInt(1);
sysout(cust_id);
rs.close();
}

stmt.close(); 
con.close();
于 2015-10-13T04:21:01.930 回答