如何在mysql服务器中获取插入的记录ID? [英] How to get the inserted record ID in mysql server?

查看:331
本文介绍了如何在mysql服务器中获取插入的记录ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有许多客户端可以访问它的MySQL服务器,并假设自己是一个客户端,并且您想要在该共享数据库中插入记录。

问题是如何保持自动增加了插入记录的表格ID?



我尝试过:



我试图使用:

 LAST_INSERT_ID()

函数返回数据库中最后一个递增的id但该函数没有用,因为许多客户端可以执行多个insert和update语句。因此,返回的id是最新的id可以被来自不同客户端的另一个update / insert语句改变。

另外,我试图使用会话变量来存储该函数返回的值

 SET @X = LAST_INSERT_ID()

但还有其他专业方法吗?

解决方案

LAST_INSERT_ID()是解决方案。看看那篇SO帖子:

SO:从mysql插入查询中获取新记录主键ID? [ ^ ]

生成的ID在服务器中维护在每个连接的基础上。这意味着函数返回给定客户端的值是为影响该客户端的AUTO_INCREMENT列的最新语句生成的第一个AUTO_INCREMENT值。



您还可以直接检查MySQL文档:

函数LAST_INSERT_ID() [ ^ ]


Suppose we have MySQL server that many clients can access it, and suppose yourself a client and you want to INSERT a record in that shared Data Base.
The question is how to hold the auto-incremented table id of the inserted record?

What I have tried:

I have tried to use :

LAST_INSERT_ID()

function that returns last incremented id in the database but this function will not be useful because many client can do multiple insert and update statements. So the returned id which is the most recent one can be altered by another update/insert statement from different client.
Also, i have tried to use a session variable to store the value returned by that function

SET @X = LAST_INSERT_ID()

But is there another professional way to do this?

解决方案

LAST_INSERT_ID() is the solution. Have a look at that SO post:
SO: Get the new record primary key ID from mysql insert query?[^]

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.


You can also check MySQL documentation directly:
Function LAST_INSERT_ID()[^]


这篇关于如何在mysql服务器中获取插入的记录ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆