JDBC obtains the Mysql auto-increment field code

Source: Internet
Author: User

Mysql aotu_increment is often used in master-slave relationships. MySQL does not have a specific sequence of oracle. In addition, the previous project used select max (*) to implement this function. Later, compared to the max (*) method, it was necessary to select the database more than once, and the efficiency was definitely not as good as that of using java.

Method 1. mysql has select LAST_INSERT_ID () to obtain the final auto_increment. Select last_insert_id () can be used to replace max (*). In this way, the auto_increment field can be set in the data table. In the case of multi-threaded concurrent operations, this method has a great advantage over max.

Method 2: Use java to provide getGeneratedKeys to obtain the final increment ID.
The code snippet is as follows:

Pstmt.exe cuteUpdate ();
Conn. commit ();
// Obtain auto_increment
Int aotuId;
Rs = pstmt. getGeneratedKeys ();
While (rs. next ()){
AutoId = rs. getInt (1 );
}

Author's "Practice record"

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.