import java.sql.*;
public class my_connect {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql: // localhost:3306/my_tutorial", "root", "test");
Statement st = con.createStatement();
String q = "INSERT INTO student (name, class, mark, sex) VALUES ('Test Name', 'Four', 73, 'male')";
st.executeUpdate(q, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = st.getGeneratedKeys();
if (rs.next()) {
int new_id = rs.getInt(1);
System.out.println("Data inserted, id is : " + new_id);
ResultSet rs2 = st.executeQuery("SELECT id, name, mark FROM student WHERE id=" + new_id);
if (rs2.next()) System.out.println(rs2.getInt(1) + " " + rs2.getString(2) + " " + rs2.getString(3));
rs2.close();
}
rs.close(); st.close(); con.close();
} catch (Exception e) { System.out.println(e); }
}
}Output:
Data inserted, id is : 43
43 Test Name 73
Omit id when inserting into our student table so MySQL generates the next key (see Auto Increment ID fields):
| Step | JDBC Code Pattern | What Happens Behind the Scenes |
|---|---|---|
| 2. Execute Query | ps.executeUpdate() |
MySQL inserts the row and generates the next AUTO_INCREMENT ID. |
| 4. Read Value | rs.next(); long id = rs.getLong(1); |
Cursor moves onto row 1 and reads the numeric key. |
Combine PreparedStatement with Statement.RETURN_GENERATED_KEYS:
import java.sql.*;
public class PreparedStatementGeneratedKeyDemo {
public static void main(String[] args) throws Exception {
String sql = "INSERT INTO student (name, class, mark, sex) VALUES (?, ?, ?, ?)";
try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost/db", "root", "test");
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, "Anita"); ps.setString(2, "Five"); ps.setInt(3, 91); ps.setString(4, "female");
ps.executeUpdate();
try (ResultSet rs = ps.getGeneratedKeys()) {
if (rs.next()) System.out.println("Generated ID: " + rs.getLong(1));
}
}
}
}Output:
Generated ID: 44
Calling getGeneratedKeys() after executeBatch() returns all generated keys in sequence:
import java.sql.*;
public class BatchGeneratedKeysDemo {
public static void main(String[] args) throws Exception {
String sql = "INSERT INTO student (name, class, mark, sex) VALUES (?, ?, ?, ?)";
try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost/db", "root", "test");
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, "A"); ps.setString(2, "Four"); ps.setInt(3, 80); ps.setString(4, "male");
ps.addBatch();
ps.setString(1, "B"); ps.setString(2, "Four"); ps.setInt(3, 85); ps.setString(4, "female");
ps.addBatch();
ps.executeBatch();
try (ResultSet rs = ps.getGeneratedKeys()) {
while (rs.next()) System.out.println("Batch ID: " + rs.getLong(1));
}
}
}
}Output:
Batch ID: 45
Batch ID: 46
Wrap key retrieval in a helper method so your Swing GUI button listener displays the new ID in a JLabel:
class StudentDao {
public static int insertAndGetId(Connection con, String name) throws SQLException {
try (PreparedStatement ps = con.prepareStatement("INSERT INTO student (name) VALUES (?)", Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, name);
ps.executeUpdate();
try (ResultSet rs = ps.getGeneratedKeys()) {
return rs.next() ? rs.getInt(1) : -1;
}
}
}
public static void main(String[] args) { System.out.println("Helper ready!"); }
}Output:
Helper ready!
JDBC getGeneratedKeys() is faster than SELECT LAST_INSERT_ID() because it avoids an extra round-trip query:
import java.sql.*;
public class LastInsertIdSqlComparison {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost/db", "root", "test");
Statement st = con.createStatement()) {
st.executeUpdate("INSERT INTO student (name) VALUES ('Ravi')", Statement.RETURN_GENERATED_KEYS);
try (ResultSet rs = st.executeQuery("SELECT LAST_INSERT_ID()")) {
if (rs.next()) System.out.println("LAST_INSERT_ID(): " + rs.getLong(1));
}
}
}
}Output:
LAST_INSERT_ID(): 47
The keys ResultSet contains column GENERATED_KEY at index 1:
import java.sql.*;
public class GeneratedKeysColumnMeta {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost/db", "root", "test");
Statement st = con.createStatement()) {
st.executeUpdate("INSERT INTO student (name) VALUES ('Temp')", Statement.RETURN_GENERATED_KEYS);
try (ResultSet rs = st.getGeneratedKeys()) {
System.out.println("Column: " + rs.getMetaData().getColumnName(1));
}
}
}
}Output:
Column: GENERATED_KEY
| Method | Thread & Concurrency Safe? | Extra Server Trips | Verdict |
|---|---|---|---|
getGeneratedKeys() |
100% Safe (Connection-Scoped) | 0 (returned in response packet) | Industry Standard |
SELECT MAX(id) FROM table |
UNSAFE (Race Condition!) | 1 extra query | Never Use (concurrency hazard) |
If you call st.executeUpdate(query) with one argument and then call st.getGeneratedKeys(), Connector/J throws SQLException: Generated keys not requested. Always pass Statement.RETURN_GENERATED_KEYS as the second parameter!
Just like a normal SELECT ResultSet, the generated keys cursor starts before the first row. Calling rs.getInt(1) before calling rs.next() throws SQLException: Before start of result set.
public class MySqlGetGeneratedKeysVerifyDemo {
public static void main(String[] args) {
if (java.sql.Statement.RETURN_GENERATED_KEYS == 1) {
System.out.println("All Java MySQL getGeneratedKeys verification checks passed!");
}
}
}Output:
All Java MySQL getGeneratedKeys verification checks passed!
Use rs.getLong(1) or rs.getInt(1) depending on whether your MySQL column is BIGINT AUTO_INCREMENT or INT AUTO_INCREMENT.
No. getGeneratedKeys() is strictly for INSERT statements that generate new auto-increment keys. For UPDATE, check the affected row count returned by executeUpdate().
If the table does not have an auto-increment column, getGeneratedKeys() returns an empty ResultSet (calling rs.next() returns false).
Yes, JDBC supports specifying target key column names, though in MySQL passing Statement.RETURN_GENERATED_KEYS is universally supported.
Check out our step-by-step tutorial: Swing JFrame to MySQL with Unique ID Display.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.