Java gets 3 ways to get the ID value of the last inserted MySQL record _java

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.