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


Have Questions? Post them here!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.