aspose file tools*
The moose likes JDBC and the fly likes Value of auto-increment column after insert Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Value of auto-increment column after insert" Watch "Value of auto-increment column after insert" New topic
Author

Value of auto-increment column after insert

Rob Sworder
Greenhorn

Joined: Nov 04, 2003
Posts: 2
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

Joined: Nov 04, 2003
Posts: 2
Found answer:
http://www.coderanch.com/t/298459/JDBC/java/last-insert-id
Moral: use search before posting!
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15300
    
    6

There is a better way.

This is much cleaner than the approach you found.


GenRocket - Experts at Building Test Data
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Value of auto-increment column after insert