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 。