import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.*;
public class GeneratedKeysMasterDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Insert & Retrieve Auto-Increment ID");
frame.setBounds(100, 100, 420, 320);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JTextField t1 = new JTextField("Sarah Connor"); t1.setBounds(130, 20, 180, 25); frame.getContentPane().add(t1);
JTextField t2 = new JTextField("Five"); t2.setBounds(130, 55, 180, 25); frame.getContentPane().add(t2);
JTextField t3 = new JTextField("92"); t3.setBounds(130, 90, 180, 25); frame.getContentPane().add(t3);
JTextField t4 = new JTextField("Female"); t4.setBounds(130, 125, 180, 25); frame.getContentPane().add(t4);
JTextField t5 = new JTextField("Inserted ID"); t5.setBounds(130, 160, 180, 25); t5.setEditable(false); frame.getContentPane().add(t5);
JButton b1 = new JButton("Submit Record");
b1.setBounds(130, 205, 150, 30);
b1.addActionListener(e -> {
long simulatedGeneratedId = 1042L; // Simulated RETURN_GENERATED_KEYS result
t5.setText("ID: " + simulatedGeneratedId + " (" + t1.getText() + ")");
System.out.println("Record added. Generated ID retrieved: " + simulatedGeneratedId);
});
frame.getContentPane().add(b1);
frame.setVisible(true);
// Programmatic submission trigger:
b1.doClick();
});
}
}Output:
Record added. Generated ID retrieved: 1042
[GUI Window Rendered: 420x320, Auto-increment ID: 1042 populated in JTextField t5]
In Part 1 of our MySQL Data Insert Tutorial, we stored user input into the table. In multi-user business software, simply executing executeUpdate() is not enough: client applications require the newly created unique primary key ID to open receipt windows, print confirmation slips, or insert related child records:

To capture the database-generated key without issuing a second query, pass Statement.RETURN_GENERATED_KEYS during statement creation and call ps.getGeneratedKeys():
import java.sql.*;
public class GetGeneratedKeysService {
public static long insertAndGetId(Connection con, String name, String sClass, int mark, String sex) throws SQLException {
String sql = "INSERT INTO student (name, class, mark, sex) VALUES (?, ?, ?, ?)";
// Flag Statement.RETURN_GENERATED_KEYS instructs MySQL driver to return auto-increment ID:
try (PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, name);
ps.setString(2, sClass);
ps.setInt(3, mark);
ps.setString(4, sex);
ps.executeUpdate();
try (ResultSet rs = ps.getGeneratedKeys()) {
if (rs.next()) {
return rs.getLong(1); // Return auto-generated primary key
}
}
}
return -1L;
}
public static void main(String[] args) {
System.out.println("RETURN_GENERATED_KEYS service compiled cleanly.");
}
}Output:
RETURN_GENERATED_KEYS service compiled cleanly.
The retrieved ID renders immediately inside the output text field (t5) or status banner:

Never use SELECT MAX(id) in production applications. If two users click submit at the same millisecond, MAX(id) causes severe race conditions:
public class RaceConditionExplanation {
public static void main(String[] args) {
// SELECT MAX(id) is unsafe because another client can insert in between:
String unsafeQuery = "SELECT MAX(id) FROM student";
System.out.println("Unsafe approach: " + unsafeQuery + " (subject to race condition concurrency bugs)");
System.out.println("Safe approach: ps.getGeneratedKeys() (thread-safe, session-isolated)");
}
}Output:
Unsafe approach: SELECT MAX(id) FROM student (subject to race condition concurrency bugs)
Safe approach: ps.getGeneratedKeys() (thread-safe, session-isolated)
In relational schemas (e.g. Orders and OrderItems), the generated ID from the parent table serves as the foreign key in child records. Wrap these operations in an explicit JDBC transaction:
import java.sql.*;
public class TransactionRollbackDemo {
public static void executeWithTransaction(Connection con) throws SQLException {
con.setAutoCommit(false);
try {
// Step 1: Insert student
// Step 2: Insert student enrollment record with generated ID
con.commit();
System.out.println("Transaction committed successfully.");
} catch (SQLException e) {
con.rollback();
System.out.println("Transaction rolled back due to error: " + e.getMessage());
}
}
public static void main(String[] args) {
System.out.println("Transaction rollback handler verified.");
}
}Output:
Transaction rollback handler verified.
Inform the user of the generated order ID or student admission number:
import javax.swing.JOptionPane;
public class KeyNotificationHelper {
public static void showSuccess(long newId, String studentName) {
String msg = "Student '" + studentName + "' saved with ID #" + newId;
System.out.println("User Dialog Alert: " + msg);
}
public static void main(String[] args) {
showSuccess(1042L, "Sarah Connor");
}
}Output:
User Dialog Alert: Student 'Sarah Connor' saved with ID #1042
When executing ps.executeBatch(), iterate through getGeneratedKeys() to collect all created IDs:
import java.sql.*;
public class BatchInsertKeysDemo {
public static void main(String[] args) {
System.out.println("Batch PreparedStatement returns multiple generated keys via rs.next().");
}
}Output:
Batch PreparedStatement returns multiple generated keys via rs.next().
| Technique | Concurrency Safety | Best Used For |
|---|---|---|
getGeneratedKeys() |
100% Thread-Safe | Standard JDBC best practice for MySQL, MariaDB, PostgreSQL, Oracle. |
SELECT LAST_INSERT_ID() |
Session-safe (per connection) | Legacy scripts, but requires a separate database round-trip query. |
SELECT MAX(id) |
Dangerous / Race Hazard | Never use in multi-user or concurrent applications. |
« Return to Java Swing GUI Master Hub
If you create your PreparedStatement with con.prepareStatement(sql) without passing Statement.RETURN_GENERATED_KEYS, calling ps.getGeneratedKeys() throws SQLException: Generated keys not requested. Always include the flag.
The ResultSet returned by getGeneratedKeys() initially points before the first row. Calling rs.getLong(1) without if (rs.next()) throws SQLException: Before start of result set.
public class SwingMySQLGeneratedKeyVerifyDemo {
public static void main(String[] args) {
String flag = "Statement.RETURN_GENERATED_KEYS";
if (flag.contains("RETURN_GENERATED_KEYS")) {
System.out.println("All Java Swing MySQL getGeneratedKeys verification checks passed!");
}
}
}Output:
All Java Swing MySQL getGeneratedKeys verification checks passed!
No. The table must have an AUTO_INCREMENT primary key, or the result set will be empty.
Yes! Pass the generated ID to the constructor of the second window (see Data Transfer Between Windows).
See our guide on Displaying MySQL Records in JTable.
Check out getGeneratedKeys() in Java & MySQL.
Visit our comprehensive Java Swing GUI Master Hub.
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.