Java three ways to get the last self increment ID value inserted into the MySQL record

  • 2020-04-01 02:09:02
  • OfStack

Method one:


String sql = "INSERT INTO users (username,password,email) VALUES (?,?,?);";
PreparedStatement pstmt = (PreparedStatement) conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);//Passed in parameter: statement.return_generated_keys
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getPassword());
pstmt.setString(3, user.getEmail());
pstmt.executeUpdate();//Perform sql                                                                                                                                                        Int autoInckey = 1;
ResultSet rs = pstmt.getGeneratedKeys(); //Getting the result & NBSP;  
if (rs.next()) {
  autoIncKey = rs.getInt(1);//Get the ID
} else {
  // throw an exception from here
}

Method 2:


SELECT MAX(id) FROM table

This method may be incorrect in cases such as multi-threading.

Method 3:


SELECT LAST_INSERT_ID()  or  SELECT @@INDENTITY 

These two are connected individually, so there is no such thing as two people being inserted at the same time
The only problem is that if you INSERT more than one, you return the first ID


Related articles: