Method One:
Copy Code code as follows:
String sql = "INSERT into users (Username,password,email) VALUES (?,?,?);";
PreparedStatement pstmt = (preparedstatement) conn.preparestatement (Sql,statement.return_generated_keys); Incoming parameters: Statement.return_generated_keys
Pstmt.setstring (1, User.getusername ());
Pstmt.setstring (2, User.getpassword ());
Pstmt.setstring (3, User.getemail ());
Pstmt.executeupdate ()//Execute SQL int autoinckey = -1;
ResultSet rs = Pstmt.getgeneratedkeys (); Get results
if (Rs.next ()) {
Autoinckey = Rs.getint (1);//Get ID
} else {
Throw an exception from
}
Method Two:
Copy Code code as follows:
SELECT MAX (ID) from table
This method may be incorrect in situations such as multithreading.
Method Three:
Copy Code code as follows:
Select last_insert_id () or select @ @INDENTITY
Both are individually connected, and there is no such thing as a so-called two-person insertion at the same time, confusing
The only problem is that if an insert inserts multiple bars, the first ID is returned.