When inserting from Java to MySQL, get Auto_Increment_ID (automatic numbering value) as the return value


Shows how to get the Auto_Increment value when inserting a record from Java code into the DB using JDBC.

You can get the last numbered value by SELECT LAST_INSERT_ID (), but you can use it when you want to get it as a return value.

usage environment


First, create the following database / table. --Database name: testdb --Table name: test

Here, prepare the id column and the Char type name column` which are the primary keys with  ĽAuto_Increment set in the test table.

The SQL to create the table is as follows.

  name CHAR(30) NOT NULL,

If you check the column information of the table (SHOW COLUMNS FROM table name), you can see that Auto_Increment is set in the id column of the primary key.

Field Type Null Key Default Extra
id int NO PRI NULL auto_increment
name char NO NULL

How to get Auto_Increment_ID

First, the Java source is shown.


public class Test {

	public static void main(String[] args) {
		 int autoIncrementKey = 0;

	     try {
	     //Driver load

	     //Connect to MySQL
	     Connection con = DriverManager.getConnection("jdbc:mysql://localhost/testdb?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", "user", "password");
	     String sql = "insert into test(name) values (?)";
         //Statement generation
	     PreparedStatement stmt = con.prepareStatement(sql, java.sql.Statement.RETURN_GENERATED_KEYS);

	     stmt.setString(1, "XXX");

         // getGeneratedKeys()By Auto_Get the Incremented ID
	     ResultSet res = stmt.getGeneratedKeys();

	    	 autoIncrementKey = res.getInt(1);



		} catch (Exception e){


When generating a PreparedStatement, set java.sql.Statement.RETURN_GENERATED_KEYSin thesecond argument.

Then, after executing the Insert statement with stmt.exceuteUpdate (), by executing stmt.getGeneratedKeys (), the automatically numbered id can be obtained.

in conclusion

There are few opportunities to use raw Java and SQL, but as a reminder.

Recommended Posts

When inserting from Java to MySQL, get Auto_Increment_ID (automatic numbering value) as the return value
[Java] Get multiple values from one return value
[Java] How to get the maximum value of HashMap
9 Corresponds to the return value
Get to the abbreviations from 5 examples of iterating Java lists
Get the ID of automatic numbering
The road from JavaScript to Java
[Java] How to convert from String to Path type and get the path
Update JAVA to the latest version to 1.8.0_144 (when downloading from the web and updating)
How to return a value from Model to Controller using the [Swift5] protocol
Don't forget to release it when you get the object from S3!
[Java small story] Monitor when a value is added to the List
How to get the value after "_" in Windows batch like Java -version
I want to get the IP address when connecting to Wi-Fi in Java
How to get the setting value (property value) from the database in Spring Framework
How to create your own annotation in Java and get the value
[Java] How to get the current directory
How to get the date in java
Precautions when migrating from VB6.0 to JAVA
[Promotion of Ruby comprehension (1)] When switching from Java to Ruby, first understand the difference.
[Java] Program example to get the maximum and minimum values from an array
Sample code to get the values of major SQL types in Java + MySQL 8.0
Connect to Aurora (MySQL) from a Java application
How to get Class from Element in Java
[Java] Get a random value from an array
[Java] How to get the redirected final URL
[Java] How to get the authority of the folder
I want to get the value in Ruby
[Java] How to get the key and value stored in Map by iterative processing
Pass arguments to the method and receive the result of the operation as a return value
[Java] How to get the URL of the transition source
Output the maximum value from the array using Java standard output
[Java] I want to calculate the difference from the date
How to write Scala from the perspective of Java
[Java] How to extract the file name from the path
Source used to get the redirect source URL in Java
As of April 2018 How to get Java 8 on Mac
I want to return a type different from the input element with Java8 StreamAPI reduce ()