Java MySQL getGeneratedKeys(): Auto-Increment Keys

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

1. How MySQL AUTO_INCREMENT and getGeneratedKeys() Work Together 🔝

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.

2. Parameterized PreparedStatement with RETURN_GENERATED_KEYS 🔝

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

3. Retrieving Multiple Auto-Increment Keys from Batch Inserts 🔝

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

4. Integrating Generated Keys with Swing GUI Forms 🔝

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!

5. Comparison: getGeneratedKeys() vs SELECT LAST_INSERT_ID() 🔝

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

6. Inspecting the Generated Keys ResultSet Structure 🔝

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

7. Why SELECT MAX(id) Causes Severe Race Conditions 🔝

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)

8. Common Developer Pitfalls & Traps 🔝

SQLException: Generated keys not requested

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!

Forgetting to Call rs.next() on GeneratedKeys

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.

9. Complete Compilable Java Program 🔝

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!

10. Frequently Asked Questions (FAQ) 🔝

What data type should I use to read the generated key?

Use rs.getLong(1) or rs.getInt(1) depending on whether your MySQL column is BIGINT AUTO_INCREMENT or INT AUTO_INCREMENT.

Does getGeneratedKeys() work with UPDATE or DELETE statements?

No. getGeneratedKeys() is strictly for INSERT statements that generate new auto-increment keys. For UPDATE, check the affected row count returned by executeUpdate().

What if the table does not have an AUTO_INCREMENT column?

If the table does not have an auto-increment column, getGeneratedKeys() returns an empty ResultSet (calling rs.next() returns false).

Can I pass column names like prepareStatement(sql, new String[]{"id"})?

Yes, JDBC supports specifying target key column names, though in MySQL passing Statement.RETURN_GENERATED_KEYS is universally supported.

Where can I see getGeneratedKeys() used in a real Swing desktop window?

Check out our step-by-step tutorial: Swing JFrame to MySQL with Unique ID Display.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer