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,

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);        

ResultSet resultSet = transaction.getGeneratedKeys();

while( {
   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!

Top Hashtags: