Java: How To Get Auto Increment Values After SQL Insert 華:如何獲得自動增加值後, SQL插入
While insert ing a SQL query we do not specify the auto increment values, if any.而插入荷蘭SQL查詢,我們不指定自動增加值,如果有的話。 However they are often required for further processing.不過,他們往往需要作進一步處理。 Here is how you can obtain auto increment / auto generated values after a successful SQL INSERT statement.在這裡,是如何可以獲取自動遞增/自動產生的價值觀後,一個成功的SQL插入聲明。
// // Insert one row that will generate an AUTO INCREMENT // key in the primary key field // stmt.executeUpdate( "INSERT INTO autoIncTest (comment) " + "values ('How can I get the auto increment field value?')", Statement.RETURN_GENERATED_KEYS); // // Use Statement.getGeneratedKeys() // to retrieve the value(s) // int autoIncValue = -1; rs = stmt.getGeneratedKeys(); if (rs.next()) { autoIncValue = rs.getInt(1); } else { // Error } rs.close(); / / / /插入一列,將產生一個自動遞增/ /關鍵在主鍵字段/ / stmt.executeupdate ( “插入autoinctest (評論) ” + “值( '我怎樣才能獲得自動遞增字段值? ' ) “ , statement.return_generated_keys ) ; / / / /使用statement.getgeneratedkeys ( ) / /檢索的價值( ) / /詮釋autoincvalue = -1 ;盧比= stmt.getgeneratedkeys ( ) ;如果( rs.next ( ) ) ( autoincvalue = rs.getint ( 1 ) ; )否則( / /錯誤) rs.close ( ) ; You can also specify and fetch multiple auto-increment key values.您也可以指定和市值多個自動增量關鍵的價值觀。 This is not just a convenience but a necessity where the primary key is also the auto increment key.這不僅是方便,而是一種需要的地方,小學的關鍵,也是自動遞增的關鍵。
Filed under提起下 Database數據庫 , , HSQLDB , HSQLDBhsqldb , , Headline News頭條新聞 , , How To如何 , , J2EE J2EE的 , , Java Software Java軟件 , , Programming編程 , , RDBMS RDBMS的 | |
| |
RSS 2.0 2.0 | |
Trackback Trackback跟踪 this Article |此文章|
Email this Article電子郵件此文章
You may also like to read您也可以想讀 |





































June 11th, 2007 at 8:42 pm 2007年6月11日在下午8時42分
This doesn’t work with postgres (at least, when I last tried it).這並不工作與postgres (至少,當我最後一次嘗試,它) 。 Instead, I use:相反,我使用:
PreparedStatement insert = conn.prepareStatement(”insert into thetable (owner, created) values (?,?); select currval(’thetable_id_seq’)”; preparedstatement插入= conn.preparestatement ( “插入thetable (所有者,創建)的價值觀(?,?);選擇currval ( ' thetable_id_seq ' ) ” ;
…
insert.execute(); insert.execute ( ) ;
if (insert.getUpdateCount() == 1 && insert.getMoreResults()) {如果( insert.getupdatecount ( ) == 1 & & insert.getmoreresults ( ) ) (
ResultSet res = insert.getResultSet();結果第= insert.getresultset ( ) ;
int id = res.getInt(1);內部id = res.getint ( 1 ) ;
} )
June 12th, 2007 at 12:34 am 2007年6月12日在上午12時34分
Thanks for sharing.感謝分享。 I have tested my code on MySQL.我已測試我的代碼在MySQL 。