can I trust mysql_insert_id() to return correct value, multithreading paranoia

和自甴很熟 提交于 2019-12-02 09:14:24

问题


I made a function that inserts a new line into a table, after calling an INSERT statement into mysql, I then make some checks, and then I check the value of mysql_insert_id().

I want to be quiet knowing that it is not possible for another thread to break in, inserting a row, before I get the result of mysql_insert_id().

My bet is that it should be safe, but I am asking because this one can be disastrous.


回答1:


From the manual:

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.

So if your threads will use separate connections, they will get different insert IDs.




回答2:


Yes you can. If mysql_insert_id() could be affected by other almost simultaneous hits to the same PHP script it would be useless.

It works on a per-connection basis.



来源:https://stackoverflow.com/questions/25505200/can-i-trust-mysql-insert-id-to-return-correct-value-multithreading-paranoia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!