MySQL and PDO: Could PDO::lastInsertId theoretically fail?

后端 未结 2 1158
深忆病人
深忆病人 2020-12-03 21:32

I have been pondering on this for a while.

Consider a web application of huge proportions, where, let\'s say, millions of SQL queries are performed every second.

相关标签:
2条回答
  • 2020-12-03 22:03

    It will always be safe provided that the PDO implementation is not doing something really bone-headed. The following is from the MySQL information on last_insert_id:

    The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

    0 讨论(0)
  • 2020-12-03 22:23

    No. lastInsertId is per-connection, and doesn't require a request to the server - mysql always sends it back in its response packet.

    So if the execute method doesn't throw an exception, then you are guaranteed to have the right value in lastInsertId.

    It won't ever give you the insert ID of anything else, unless your query failed for some reason (e.g. invalid syntax) in which case it might give you the insert ID from the previous one on the same connection. But not anybody else's.

    0 讨论(0)
提交回复
热议问题