how to get last inserted id from database
Hello,
In PHP Language, mysql_insert_id() gives the last inserted ID without writing any Queries in the code. Is there similar mechanism to do in Jsp page. I need to insert data in one table and in the meantime, with the last inserted ID i need to insert another sort of data in another table.
Can u plz help me out?
[335 byte] By [
yubak123a] at [2007-11-27 0:26:30]

# 1
You can use Statement#getGeneratedKeys().
The DDL should look like at least (you can use INT UNSIGNED instead, your choice):ID BIGINT AUTO_INCREMENT PRIMARY KEY
Basic example:int affectedRows = statement.executeUpdate("INSERT INTO table (column1, column2) VALUES ('value1', 'value2')");
Long insertID = null;
if (affectedRows == 1) {
ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
insertID = new Long(generatedKeys.getLong(1));
}
}
Using MySQL Connector/J 5.0.