Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DB2 Sequence value using Java

Tags:

java

jdbc

db2

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?

like image 225
Jayp Avatar asked Feb 12 '13 12:02

Jayp


People also ask

How do you find the current value of a sequence in db2?

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.

What is sequence object in db2?

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.


2 Answers

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.

like image 156
Jayp Avatar answered Sep 27 '22 19:09

Jayp


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)

like image 23
Xavi López Avatar answered Sep 27 '22 18:09

Xavi López