package org.kodejava.example.jdbc;
import java.sql.*;
public class GetGeneratedKeyExample {
private static final String URL = "jdbc:mysql://localhost/kodejava";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
public static void main(String[] args) {
try (Connection connection =
DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
// The orders table have an ID column which value will be auto
// generated by database. When inserting a new record a new id
// for the primary key will be generated and we will get the
// generated key so we can used it in another process. For
// instance if we have a master detail tables where the details
// table required an id from the master table.
String sql = "INSERT INTO orders (username, order_date) " +
"VALUES ('foobar', '2018-11-12')";
Statement stmt = connection.createStatement();
// When executing the statement we can pass the
// Statement.RETURN_GENERATED_KEYS so that we can later extract
// the generated key from the result set object returned by
// this method.
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet keys = stmt.getGeneratedKeys();
int lastKey = 1;
while (keys.next()) {
lastKey = keys.getInt(1);
}
System.out.println("Last Key: " + lastKey);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The structure of orders
table.
CREATE TABLE `orders` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`order_date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
Maven dependencies
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020