Friday, September 4, 2026

Java MySQL: Get the Last Inserted ID Using JDBC

I have faced many questions and problems related to retrieving the ID of the last inserted record when using MySQL as the backend.

When a table has an auto-increment primary key, we may need to retrieve the generated ID immediately after inserting a record.

In Java JDBC, this can be done using Statement.RETURN_GENERATED_KEYS and getGeneratedKeys().

Example

String query = "INSERT INTO m_time_list " +
               "(vchTime, vchGMT, createdDate) " +
               "VALUES (?, ?, CURDATE())";

PreparedStatement pstmt =
        connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);

pstmt.setString(1, form.getTxtTime());
pstmt.setString(2, form.getRdbgmt());

pstmt.executeUpdate();

ResultSet rs = pstmt.getGeneratedKeys();

int sid = 0;

if (rs.next()) {
    sid = rs.getInt(1);
}

System.out.println("Generated ID: " + sid);

After the insert is executed, sid contains the generated auto-increment ID.

Using MySQLLAST_INSERT_ID()

MySQL also provides the LAST_INSERT_ID() function for obtaining the automatically generated ID.

SELECT LAST_INSERT_ID();

For Java applications using JDBC, however, Statement.RETURN_GENERATED_KEYS with getGeneratedKeys() is generally a convenient way to retrieve the generated key directly from the insert operation.


Note: Use PreparedStatement parameters rather than concatenating user-provided values directly into an SQL string. This helps avoid SQL injection and also handles parameter values correctly.

No comments:

Post a Comment