java - Is there a way to retrieve the autoincrement ID from a prepared statement -


is there way retrieve auto generated key db query when using java query prepared statements.

for example, know autogeneratedkeys can work follows.

stmt = conn.createstatement();  stmt.executeupdate(sql, statement.return_generated_keys); if(returnlastinsertid) {     resultset rs = stmt.getgeneratedkeys();     rs.next();     auto_id = rs.getint(1); }  

however. if want insert prepared statement.

string sql = "insert table (column1, column2) values(?, ?)"; stmt = conn.preparestatement(sql);  //this error stmt.executeupdate(statement.return_generated_keys); if(returnlastinsertid) {     //this error since above error     resultset rs = stmt.getgeneratedkeys();     rs.next();     auto_id = rs.getint(1); }  

is there way don't know about. seems javadoc preparedstatements can't return auto generated id.

yes. see here. section 7.1.9. change code to:

string sql = "insert table (column1, column2) values(?, ?)"; stmt = conn.preparestatement(sql, statement.return_generated_keys);   stmt.executeupdate(); if(returnlastinsertid) {    resultset rs = stmt.getgeneratedkeys();     rs.next();    auto_id = rs.getint(1); } 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -