This post provides code example that gets the value of the newly inserted record in database using JDBC.

Some database operations, especially those involving parent-child relationships (one-to-many), you may want to insert a record into the parent table first, then into the child table. But the records in the child table must have a foreign key that refers to the parent table’s primary key. In such case, you need a technique that retrieves the value of the primary key of the last record inserted (usually auto-incremented by the database engine). JDBC provides such mechanism but implementation is slightly different for different database systems.

For MySQL and Java Derby database, use the following code:

        String sql = "YOUR INSERT STATEMENT HERE";

        PreparedStatement ps = conn.prepareStatement(sql,
                Statement.RETURN_GENERATED_KEYS);

        ps.execute();

        ResultSet rs = ps.getGeneratedKeys();
        int generatedKey = 0;
        if (rs.next()) {
            generatedKey = rs.getInt(1);
        }

        System.out.println("Inserted record's ID: " + generatedKey);

 

For Oracle database, use the following code:

        PreparedStatement statement = conn.prepareStatement(sql,
                Statement.RETURN_GENERATED_KEYS);

        statement.execute();

        PreparedStatement ps = connection
                .prepareStatement("select your_table_id_sequence.currval from dual");

        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            generatedKey = (int) rs.getLong(1);
        }

        System.out.println("Inserted record's ID: " + generatedKey);

Note: for Oracle database, you should create a sequence for the table’s primary key.

 

Other JDBC Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#3akash2021-05-28 12:37
document.write("Welcome to Javatpoint");
Quote
#2sherlin2020-03-21 00:09
Hi I'm developing a web project using Jsp.

What if the insert statement is another page?
Quote
#1sherlin2020-03-21 00:01
PreparedStatement statement = conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);


What is "sql" in this statement?
Quote