How to get the insert ID in JDBC?
⚡TLDR
To instantly fetch the last insert ID in JDBC, use the mega-helpful getGeneratedKeys() method. Execute it post-insert to collect a fresh auto-generated key via ResultSet. Here's the cheat-code:
Replace myTable and the INSERT values to match your *ahem* EVIL PLANS. End scheme.
Stomach various databases
Be mindful! The chameleons we call databases need specific strategies for retrieving the automatically-generated insert ID:
- MySQL and DB2: Just follow the Fast answer, they are type
easyMode. - Oracle: You can adopt the
getGeneratedKeys()method, though theRETURNINGclause in anINSERTstatement or aCallableStatementare also good confidants. - PostgreSQL: Easy-peasy now due to recent updates, practically a sibling to MySQL and DB2 with
RETURN_GENERATED_KEYS. - SQL Server: After INSERT, execute a boss move
SELECT @@IDENTITYto pull the last insert ID. But watch for sneaky concurrent inserts!
Remember to inspect driver-specific scrolls (also known as documentation) to capture subtle behaviours of their JDBC implementation.
Best practices to rob(insert, not literally!) and run
Brace for INSERT storm
- Operation Successful?: Verify
executeUpdate()was a victorious cause (returns more than zero), confirming an insert before ID retrieval. - Handle with Care: Encase your JDBC endeavours within
try-catchmagic circles for graceful handling of exceptions. - Close all Portals: Employ
try-with-resourcesmagic for yourPreparedStatementandResultSetto assure all the Rifts (resources) are closed.
Prepare for parallel threats
- Single-Threaded Champions: In moments of dealing with
SELECT @@IDENTITYin SQL Server, you might resort to a one-man-army approach to fetch accurate ID amid other transactions. - Be Isolated, Stay Undisturbed: Call upon the spirit of transaction isolation to guard against dirty reads affecting your insert ID.
Choose your weapon (platform) wisely
Engaging with JDBC drivers, reckon the following:
- Oracle JDBC: Invoke
CallableStatement.getGeneratedKeys()or conjure a query withRETURNINGintoResultSet. - MySQL JDBC: Unleash
getGeneratedKeys()on aPreparedStatementorStatementlike an almighty spell. - PostgreSQL JDBC: Consider the
RETURNINGclause right in theINSERTstatement, or use thegetGeneratedKeys()method.
Linked
Linked
Was this article helpful?