How to Get the Insert ID in JDBC? Last Updated : 05 Apr, 2024 Summarize Comments Improve Suggest changes Share Like Article Like Report In Java, for getting the insert ID in JDBC, we have built-in methods like getGeneratedKeys(). This method can be able to get the inserted ID in JDBC. Here, in this article, we have used PreparedStatement for insertion purposes and the SQL Injection attack free also. After performing an insertion operation on the database, we can retrieve the ID which is automatically generated. This ID is known as insert ID and often it is used as the primary key in the database. In this article, we will learn about how to get the inserted ID from the table in the JDBC. Below we have provided the related example with the output image for reference. Steps to Get the Inserted IDEstablish Database ConnectionPrepare SQL StatementSet Parameter ValuesExecute Insert OperationRetrieve Auto-generated KeysRetrieve Insert IDGet the Insert ID in JDBCWe have getGeneratedKeys() method in the PreparedStatement interface. This method can be able to get the generated keys while inserting data into a table and the ID is often used as the primary key in the table. For getting insert ID in JDBC, first, we need to connect with the database by using JDBC connection properties like domain name, username, password and database name we want to connect. Once the connection is successful, then we take sample data and insert by using PreparedStatement.Then, we have used ResultSet. It is used to run the SQL queries. Then we hold the insert ID and finally, it prints that ID as output. We have created a table with a name book with four columns id, author, name, and price. Below is the Table for reference. Table:Java Program to get the insert ID in JDBCBelow is the code implementation to get the generated keys in JDBC. Java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class InsertedIdExample { public static void main(String[] args) { try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/books", "root", "password"); // Create a PreparedStatement with the SQL statement and RETURN_GENERATED_KEYS option String sql = "INSERT INTO book (author, name, price) VALUES (?, ?, ?)"; PreparedStatement stmt = con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS); // Set values for the parameters stmt.setString(1, "Gupta"); stmt.setString(2, "My Book"); stmt.setDouble(3, 29.99); // Execute the insert operation int rowsAffected = stmt.executeUpdate(); if (rowsAffected > 0) { // Retrieve the auto-generated keys (insert ID) ResultSet generatedKeys = stmt.getGeneratedKeys(); if (generatedKeys.next()) { int insertId = generatedKeys.getInt(1); System.out.println("Record inserted successfully with ID: " + insertId); } else { System.out.println("Failed to retrieve insert ID."); } } else { System.out.println("No records inserted."); } con.close(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } } OutputBelow we can see the console output:Database Table Output:Explanation of the above Program:First, we establish a connection to the MySQL database by using DriverManager.getConnection. Then we prepare an insert SQL statement with placeholders for parameters using the PreparedStatement interface.After this, we set values for the parameters using set method with related data type. Then we execute the insert operation using executeUpdate. After this, we retrieve the auto-generated keys using getGeneratedKeys() method of the PreparedStatement. Finally, we retrieve the insert ID from ResultSet and print it out. Comment More infoAdvertise with us Next Article How to Handle SQL Injection in JDBC using PreparedStatement? E eswararaobetha1 Follow Improve Article Tags : Java Java Programs JDBC Practice Tags : Java Similar Reads Java Program to Insert Details in a Table using JDBC Java Database Connectivity is basically a standard API(application interface) between the java programming language and various databases like Oracle, SQL, Postgres, SQL, etc. It connects the front end(for interacting with the users ) with the backend( for storing data). Algorithm: Search/ Insert/ D 4 min read How to Perform a Bulk Insertion using JDBC? Performing a bulk insert using JDBC involves using the PreparedStatement interface and addBatch() method. This addBatch() method increases the performance while data is inserted into a database. In this article, we will learn how to perform a bulk insert using JDBC. Approach:For this, we need to cre 4 min read How to Create a Statement Object in JDBC ? JDBC stands for Java Database Connectivity. It is used in Java-based API which allows Java Applications to interact and perform operations on relational databases. Creating a "Statement" object in JDBC is an important step while dealing with a database in Java. A "Statement" object is used to execut 4 min read How to Handle SQLException in JDBC? Java Database Connectivity (JDBC) serves as the backbone for Java applications when interacting with databases. While establishing connections and executing queries, we developers often encounter SQLExceptions, which are inevitable in the real world. Handling those exceptions is crucial in the devel 4 min read How to Handle SQL Injection in JDBC using PreparedStatement? In this article, we can learn how to prevent SQL injection in JDBC by using Java programming. Basically, SQL injection is a type of security vulnerability It occurs when hackers or attackers can change or manipulate the SQL query, and this can lead to unauthorized access to resources and also perfor 4 min read How to Handle NULL Values in JDBC? Java programming can be able to handle databases by using JDBC API. In this article, we will discuss how to handle NULL values in JDBC. For this problem, we have inserted some data into an already created table named book in my Database named books. To handle null values in JDBC involves checking fo 4 min read Like