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

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!