I need to get the next value from a DB2 sequence. This is one approach I've tried
stmt = con.createStatement();
rs = stmt.executeQuery("db2 VALUES NEXTVAL FOR <sequence_name>");
rs.close();
stmt.close();
The error I get is as follows:
com.ibm.db2.jcc.c.SqlException: [ibm][db2][jcc][10103][10941] Method executeQuery cannot be used for updates.
at com.ibm.db2.jcc.c.qh.a(qh.java:2390)
at com.ibm.db2.jcc.c.qh.a(qh.java:1751)
at com.ibm.db2.jcc.c.qh.a(qh.java:478)
at com.ibm.db2.jcc.c.qh.executeQuery(qh.java:462)
at test.pack.SequenceConn.getNextSequenceValue(SequenceConn.java:59)
at test.pack.SequenceConn.main(SequenceConn.java:22)
How can I retrieve the next value from the sequence?
You can access the value of a sequence using the NEXTVAL or CURRVAL operators in SQL statements. You must qualify NEXTVAL or CURRVAL with the name (or synonym) of a sequence object that exists in the same database, using the format sequence. NEXTVAL or sequence. CURRVAL.
A sequence is a user-defined object that generates a sequence of numeric values according to the specification with which the sequence was created. Sequences, unlike identity columns, are not associated with tables. Applications refer to a sequence object to get its current or next value.
Managed to solve this by myself.
stmt = con.createStatement();
rs = stmt.executeQuery("VALUES NEXTVAL FOR <sequence_name>");
rs.close();
stmt.close();
Basically the preceding db2
in the query string was causing the issue. Removed it and was able to get the sequence value.
You can use the following sentence to retrieve the next value for a sequence in DB2:
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT NEXT VALUE FOR <sequence_name>");
if(rs.next()) {
Long sequenceValue = rs.getLong(1);
}
rs.close();
stmt.close();
As specified in the DB2 Reference chapter on Sequences.
NEXT VALUE FOR sequence-name
A NEXT VALUE expression generates and returns the next value for the sequence specified by sequence-name.
...
- NEXT VALUE and PREVIOUS VALUE expressions can be specified in the following places:
· select-statement or SELECT INTO statement (within the select-clause, provided that the statement does not contain a DISTINCT keyword, a GROUP BY clause, an ORDER BY clause, a UNION keyword, an INTERSECT keyword, or EXCEPT keyword)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With