Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Value of auto-increment column after insert

 
Rob Sworder
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've used the following code in php to get the auto-incremented primary key column value returned after an insert:
$sql = "insert into mytable (columnB) values ('Test')";
$columnA = mysql_insert_id();
I haven't been able to repeat this in Java. I have tried:
int columnA;
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rst = stmt.executeQuery("select * from mytable");
rst.moveToInsertRow();
rst.updateString(2, 'Test');
rst.insertRow();
columnA = rst.getInt(1);
//For a table:
// create table mytable (columnA int auto_increment primary key,
// columnB varchar(10));
Many Thanks
 
Rob Sworder
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Found answer:
http://www.coderanch.com/t/298459/JDBC/java/last-insert-id
Moral: use search before posting!
 
Gregg Bolinger
GenRocket Founder
Ranch Hand
Posts: 15302
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a better way.

This is much cleaner than the approach you found.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic