2013-02-12 90 views
3

我需要從DB2序列中獲取下一個值。這是一個方法我試過DB2使用Java的序列值

stmt = con.createStatement(); 
rs = stmt.executeQuery("db2 VALUES NEXTVAL FOR <sequence_name>"); 

rs.close(); 
stmt.close(); 

我得到的錯誤如下:

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) 

我怎樣才能檢索順序的下一個值?

回答

3

自己解決這個問題。

stmt = con.createStatement(); 
rs = stmt.executeQuery("VALUES NEXTVAL FOR <sequence_name>"); 

rs.close(); 
stmt.close(); 

基本上前面的db2在查詢字符串中引起了問題。刪除它,並能夠獲得序列值。

1

您可以使用如下語句來檢索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(); 

正如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)

+0

感謝您的提示!嘗試一下,並偶然發現了下一個錯誤:com.ibm.db2.jcc.c.SqlException:DB2 SQL錯誤:SQLCODE:-104,SQLSTATE:42601,SQLERRMC:END-OF-STATEMENT; READ FOR ; 。很快嘗試谷歌解決方案,但迄今尚未找到。 – Jayp 2013-02-12 12:34:08

+0

@Jayp:不要在Java的SQL字符串中包含';'。並且每次調用'executeQuery()'只執行一條SQL語句。 – 2013-02-12 12:45:21

+0

這個字符串和上面的哈維完全一樣。 – Jayp 2013-02-12 12:46:42