Thread safely gets the ID of the entry that was inserted into MySQL

Source: Internet
Author: User

when inserting an entry into MySQL, you sometimes want to get the ID of the inserted entry, one way is to execute a SELECT statement condition for MAX (ID) to get, but this form is not thread-safe in the concurrency environment, Because there may already be another entry inserted between your completion insert and the maximum ID that is executed again to perform a select.

A thread-safe solution is to use the Select LAST_INSERT_ID () statement, which returns the ID of the first inserted entry in this link (each database link is assumed by a thread)

eg.

(1), in connection 1 to a table insert a record, a table contains an ID of auto_increment type.

(2), in connection 2 to a table and then insert a record.

(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.

Also, when using select LAST_INSERT_ID (), be aware that when inserting multiple records at one time, just get the first inserted ID value, be careful!

Thread safely gets the ID of the entry that was inserted into MySQL

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.