Skip to content

Instantly share code, notes, and snippets.

@kaweski
Last active January 11, 2017 19:38
Show Gist options
  • Save kaweski/4e0af82f5a14decf7938a6d06c19ec85 to your computer and use it in GitHub Desktop.
Save kaweski/4e0af82f5a14decf7938a6d06c19ec85 to your computer and use it in GitHub Desktop.
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment