naweskil
11/15/2016 - 10:28 PM

RETURN_GENERATED_KEYS

RETURN_GENERATED_KEYS

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {
  private static final String URL = "jdbc:mysql://localhost/testdb";

  private static final String USERNAME = "root";

  private static final String PASSWORD = "";

  public static void main(String[] args) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);

    String insert = "INSERT INTO orders (username, order_date) VALUES ('foobar', '2007-12-13')";
    Statement stmt = conn.createStatement();

    stmt.executeUpdate(insert, Statement.RETURN_GENERATED_KEYS);

    ResultSet keys = stmt.getGeneratedKeys();
    int lastKey = 1;
    while (keys.next()) {
      lastKey = keys.getInt(1);
    }
    System.out.println("Last Key: " + lastKey);
    conn.close();
  }
}