ash__999 ash__999 - 9 months ago 27
Java Question

How to return the autoincremented BIGINT key of the row inserted in MySQL through JDBC?

I have a table, say

with an autoincremented primary key of type BIGINT.

In Java, I'm looking to

  • insert a row to

  • return the key of that row inserted.

I tried the following without much expectations since the key field of
is returning an integer array.

String query2 = "INSERT INTO Users (name, status) VALUES (?, ?); "
// ... code deleted for clarity
int [] tmp = pStat.executeBatch();

The array returned out of this code is empty.

How to do this in MySQL?

I've seen Get the new record primary key ID from mysql insert query? and some other relevant discussions.


Answer Source

You need to pass Statement.RETURN_GENERATED_KEYS as one of the arguments while creating preparedstatement, have a look at javadoc here:

autoGeneratedKeys - a flag indicating whether auto-generated keys should be returned; one of Statement.RETURN_GENERATED_KEYS or Statement.NO_GENERATED_KEYS

Code would look like this:

PreparedStatement pStat = connection.prepareStatement(SQL_INSERT,

Once the statement gets executed, you can get the keys via getGeneratedKeys() method (javadoc here):

ResultSet rsKeys = statement.getGeneratedKeys();
//Iterate the resultset using next
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download