Java JDBC Get Id of the Inserted Record with AutoIncrement


If you inserted a record into a database table and you have an auto-incremented ID which you passed in as null, and to continue further you want the Id that was set for that record in the database?

You can pass in the column names that you want in the ResultSet as a part of the PrepareStatement as shown in the below code snippet,

Example:
String generatedId[] = { "book_id" };
String insertRecordBook = "insert into  books(book_id,book_name) values(?,?)";
Connection connection = DriverManager.getConnection(url,userName,password);|
PreparedStatement transaction = connection.prepareStatement(insertRecordBook,generatedId);

transaction.setObject(1, null);
transaction.setString(2, bookName);        
transaction.executeUpdate();

ResultSet resultSet = transaction.getGeneratedKeys();

while(resultSet.next()) {
   bookId = resultSet.getInt(1);
   System.out.println("book_Id:" + bookId);
}
Output: book_Id: 2
Get the Auto-generated ID using Java JDBC
Get the Auto-generated ID using Java JDBC
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap