Get the value of the self-growth ID just inserted in Mysql

Source: Internet
Author: User

1 INSERT INTO user (Username,password) VALUES ('zyl','123' );    2 // gets the value of the self-growth ID just inserted 3 Select last_insert_id ();   

In MySQL, using the ID field of the Auto_increment type as the primary key for the table, and use it as a foreign key for other tables, forms a "master-detail table structure," which is a common use in database design. However, when the ID is generated, our sequence of operations is usually to insert a record in the primary table and then get the auto-generated ID to insert the record from the table based on it. There is a difficulty in how to get the ID of the main table after inserting it. The usual practice is through "SELECT Max (ID) from tablename" approach, but obviously this practice needs to consider concurrency, need to be in the transaction "x lock" the main table, to obtain the value of Max (ID), and then unlock. This approach requires a lot of steps, some trouble, and a bad concurrency. Is there a simpler way to do it? One of the answers is through the Select last_insert_id () operation. At first glance, it looks like select Max (ID), but it's actually thread-safe. This means that it is specific to the database connection. The following experiment illustrates:
1, insert a record into table A in connection 1, a table contains a field of type Auto_increment.
2. In connection 2, insert a record into table A.
3, Result: The result of executing select last_insert_id () in connection 1 is different from the result of executing select last_insert_id () in connection 2, and the result of executing select MAX (ID) in two connections is the same.

Actually the difference between scope_identity () and Ident_current () in MSSQL is similar here. Use Scope_identity () to get the value of the current session in which an identity field is inserted, and using ident_current () will get the maximum value inserted on an identity field without distinguishing between different sessions.
Note: When using select LAST_INSERT_ID (), be aware that when inserting multiple records at one time, just get the ID value of the first insertion, be careful! Try

INSERT into TB (C1,C2) VALUES (C1value,c2value), (c1value1,c2value2) ...

Finally, there is a problem that has not been solved:

When using select LAST_INSERT_ID (), it is important to note that when multiple records are inserted at one time, only the ID value that is inserted for the first time is obtained.

When we write a database program, we often need to get the maximum number of numbers in a table,
In general, it is possible to get the ID of the data just inserted, using SELECT Max (ID) from table.
But in the case of multithreading, it is not.

Here are three ways to

(1) Getgeneratedkeys () method:

Program Snippet:

1Connection conn = ; 2Serializable ret =NULL; 3PreparedStatement state = .; 4ResultSet rs=NULL; 5     Try {   6 state.executeupdate (); 7rs =State.getgeneratedkeys (); 8         if(Rs.next ()) {9ret = (Serializable) rs.getobject (1); Ten         }          One}Catch(SQLException e) { A     }    -     returnRet

(2) LAST_INSERT_ID:

LAST_INSERT_ID is not related to table, last_insert_id will change if data is inserted into table A, and then the data is injected into form B.

Max (ID) is obviously not available in the case where multiple users are alternately inserting data.
This should use last_insert_id, because last_insert_id is connection based, as long as each thread uses a separate connection object, Last_insert_ The ID function returns the ID of the first record generated by the connection for the latest insert or update* of the auto_increment column. This value cannot be affected by other clients (Connection), which guarantees that you will be able to retrieve your ID without worrying about other clients ' activities and do not need to lock. Insert multiple records using a single INSERT statement, LAST_INSERT_ID returns a list.

(3) SELECT @ @IDENTITY:

Display code

1 String sql= "SELECT @ @IDENTITY";   

@ @identity is a system-defined global variable that represents the last time the value of the self-increment column for inserting data into a table with the identity attribute (that is, the self-increment column). General system-defined global variables start with @@ 开头 and user-defined variables begin with @. For example, there is a table A, its self-increment column is an ID, when inserting a row of data into a table, if the value of the self-increment after inserting data automatically increases to 101, then the value obtained by the SELECT @ @identity is 101. The @ @identity is used only if the connection is not closed when the insert operation is executed, or a null value is obtained.

Get the value of the self-growth ID just inserted in Mysql

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.