Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Value of auto-increment column after insert

 
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:
https://coderanch.com/t/298459/JDBC/java/last-insert-id
Moral: use search before posting!
 
Ranch Hand
Posts: 15304
6
Mac OS X IntelliJ IDE Chrome
  • 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.
 
I don't like that guy. The tiny ad agrees with me.
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic