Statement.RETURN_GENERATED_KEYS : Statement « java.sql « Java by API






Statement.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();
  }
}

   
  








Related examples in the same category

1.Statement.EXECUTE_FAILED
2.Statement.SUCCESS_NO_INFO
3.Statement: addBatch(String sql)
4.WebRowSet: execute(Connection conn)
5.Statement: executeBatch()
6.Statement: executeQuery(String sql)
7.Statement: getFetchSize()
8.Statement: getGeneratedKeys()
9.Statement: getMaxFieldSize()
10.Statement: getMaxRows()
11.Statement: getQueryTimeout()
12.WebRowSet: setCommand(String cmd)
13.Statement: setFetchSize(int rows)