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!

Top Hashtags:

Advertisements

Advertisements




Advertisements