MySQL 的 Select Last_Insert_ID 的线程安全
Thread safety of MySQL's Select Last_Insert_ID
我正在尝试在 MySQL 上也 运行 制作一些 SQL 服务器代码,但我恰好碰到了这个地雷。 Google 说正常的方法是简单地进行插入,然后 select last_insert_ID() 找出写入的内容。
不过,这在多用户环境中并不安全。那里有一个狭窄的 window,另一个用户可以在其中插入一些东西并导致错误的 return 值。如何安全插入并获取插入记录的key?
来自LAST_INSERT_ID(), LAST_INSERT_ID(expr)
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.
因此,除非您对多个用户的插入恰好是通过同一个数据库连接进行的,否则您无需担心。
那么使用它安全吗?这是我的功能:
$id=mysqli_insert_id($conn);
mysqli_close($conn);
这是我返回的函数的最新两条语句 return $id;
我正在尝试在 MySQL 上也 运行 制作一些 SQL 服务器代码,但我恰好碰到了这个地雷。 Google 说正常的方法是简单地进行插入,然后 select last_insert_ID() 找出写入的内容。
不过,这在多用户环境中并不安全。那里有一个狭窄的 window,另一个用户可以在其中插入一些东西并导致错误的 return 值。如何安全插入并获取插入记录的key?
来自LAST_INSERT_ID(), LAST_INSERT_ID(expr)
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.
因此,除非您对多个用户的插入恰好是通过同一个数据库连接进行的,否则您无需担心。
那么使用它安全吗?这是我的功能:
$id=mysqli_insert_id($conn);
mysqli_close($conn);
这是我返回的函数的最新两条语句 return $id;