Sunday 22 March 2020

Get Generated id in jdbc

Using 'getGeneratedKeys()' method of PreparedStatement we can get the generated keys.

Example
private static void createEmployee(Employee emp) throws SQLException {
 String stmtToInsert = "INSERT INTO employee(firstName, lastName) values (?, ?)";
 try (PreparedStatement statement = connection.prepareStatement(stmtToInsert,
   Statement.RETURN_GENERATED_KEYS);) {
  statement.setString(1, emp.getFirstName());
  statement.setString(2, emp.getLastName());

  int affectedRows = statement.executeUpdate();

  if (affectedRows == 0) {
   throw new SQLException("Creating Employee failed, no rows affected.");
  }

  try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
   if (generatedKeys.next()) {
    emp.setId(generatedKeys.getInt(1));
   } else {
    throw new SQLException("Creating Employee failed, no ID obtained.");
   }
  }
 }
}

Find the below working application.

App.java
package com.sample.app;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import com.sample.app.model.Employee;

public class App {

 // Initialize url username and password
 private static final String URL = "jdbc:mysql://localhost/sample";
 private static final String USERNAME = "krishna";
 private static final String PASSWORD = "krishna";

 private static Connection connection = null;

 private static void createEmployee(Employee emp) throws SQLException {
  String stmtToInsert = "INSERT INTO employee(firstName, lastName) values (?, ?)";
  try (PreparedStatement statement = connection.prepareStatement(stmtToInsert,
    Statement.RETURN_GENERATED_KEYS);) {
   statement.setString(1, emp.getFirstName());
   statement.setString(2, emp.getLastName());

   int affectedRows = statement.executeUpdate();

   if (affectedRows == 0) {
    throw new SQLException("Creating Employee failed, no rows affected.");
   }

   try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
    if (generatedKeys.next()) {
     emp.setId(generatedKeys.getInt(1));
    } else {
     throw new SQLException("Creating Employee failed, no ID obtained.");
    }
   }
  }
 }

 public static void main(String args[]) throws SQLException, ClassNotFoundException {

  /* Open connection to database */
  System.out.println("Connecting to database");

  connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

  /* Create table employee */
  String query = "CREATE TABLE employee (id int NOT NULL AUTO_INCREMENT, firstName varchar(30), lastName varchar(30), PRIMARY KEY(id))";
  Statement stmt = connection.createStatement();
  stmt.execute(query);

  /* Insert data to employee table */
  Employee emp1 = new Employee("Krishna", "Gurram");
  Employee emp2 = new Employee("Gopi", "Battu");

  createEmployee(emp1);
  createEmployee(emp2);

  System.out.println("Employee1 id : " + emp1.getId());
  System.out.println("Employee2 id : " + emp2.getId());

  query = "SELECT id, firstName, lastName FROM employee";
  ResultSet resultSet = stmt.executeQuery(query);
  ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
  String columnName1 = resultSetMetaData.getColumnName(1);
  String columnName2 = resultSetMetaData.getColumnName(2);
  String columnName3 = resultSetMetaData.getColumnName(3);

  System.out.println(columnName1 + " " + columnName2 + " " + columnName3);

  while (resultSet.next()) {
   int id = resultSet.getInt("id");
   String firstName = resultSet.getString("firstName");
   String lastName = resultSet.getString("lastName");
   System.out.println(id + " " + firstName + " " + lastName);
  }

  System.out.println("Dropping the table employee");

  String sql = "DROP TABLE employee";

  stmt.executeUpdate(sql);

  resultSet.close();
  connection.close();
  connection.close();
 }
}

Output

Connecting to database
Employee1 id : 1
Employee2 id : 2
id firstName lastName
1 Krishna Gurram
2 Gopi Battu
Dropping the table employee



Previous                                                    Next                                                    Home

No comments:

Post a Comment