package org.kodejava.jdbc;
import java.sql.*;
public class GetGeneratedKeyExample {
private static final String URL = "jdbc:mysql://localhost/kodejava";
private static final String USERNAME = "kodejava";
private static final String PASSWORD = "s3cr*t";
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 use 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 purchase_order (username, order_date)
VALUES ('foobar', '2021-09-25')
""";
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 statement object after executing
// the query.
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet keys = stmt.getGeneratedKeys();
long lastKey = 1L;
while (keys.next()) {
lastKey = keys.getLong(1);
}
System.out.println("Last Key: " + lastKey);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The structure of purchase_order
table.
CREATE TABLE `purchase_order`
(
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`order_date` date NOT NULL,
PRIMARY KEY (`id`)
);
Maven Dependencies
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024