[英]Problem with MySQL's LAST_INSERT_ID()
I am having a problem with LAST_INSERT_ID()
. 我对
LAST_INSERT_ID()
有问题。
Every time I use it I need to open and close a new connection. 每次使用它时,我都需要打开和关闭一个新连接。 This slows down my application a great deal.
这大大减慢了我的应用程序的速度。 i need to do many insert statements end get for each one his inserted id all on the same connection!
我需要做很多insert语句,每个插入的end都将在同一连接上插入的ID。 How can I get the last inserted ID on the same connection for with MySQl, ODBC and C# from a specific table with no concurrency problems?
如何在没有并发问题的情况下从特定表中获取与MySQl,ODBC和C#相同连接的最后插入的ID?
here is my code: 这是我的代码:
#region Private Variables
private static DataAccess _DataAccess = null;
private static object _SyncLock = new object();
private OdbcConnection myConnection = null;
#endregion
#region Instance Method
public static DataAccess Instance
{
get
{
lock (_SyncLock)
{
if (_DataAccess == null)
_DataAccess = new DataAccess();
return _DataAccess;
}
}
}
#endregion
#region Constractors
public DataAccess()
{
myConnection = new OdbcConnection(stringConnDB);
myConnection.Open();
}
#endregion
Every time I use it i need to open and close a new connection
每次使用它时,我都需要打开和关闭一个新的连接
No, you don't need a new connection. 不,您不需要新的连接。 You are supposed to use it on the same connection just after an insert statement.
您应该在插入语句之后在同一连接上使用它。
The ID that was generated is maintained in the server on a per-connection basis .
生成的ID在每个连接的服务器中维护。 This means that the value returned by [
LAST_INSERT_ID
] to a given client is the firstAUTO_INCREMENT
value generated for most recent statement affecting anAUTO_INCREMENT
column by that client .这意味着,通过[返回值
LAST_INSERT_ID
]给定的客户端是第一个AUTO_INCREMENT
近期影响的大多数语句生成值AUTO_INCREMENT
该客户端柱。 This value cannot be affected by other clients, even if they generateAUTO_INCREMENT
values of their own.即使其他客户端生成自己的
AUTO_INCREMENT
值,该值也不会受到其他客户端的影响。 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,而不必担心其他客户端的活动,也不需要锁或事务。
Why do you think that you need to open a new connection? 为什么您认为需要打开一个新连接? Actually you should not open a new connection, you should use
last_insert_id()
on the same connection to be sure to get the correct result. 其实你不应该打开一个新的连接,你应该使用
last_insert_id()
相同的连接上,就一定要得到正确的结果。
If you have tried it with a new connection and it seems to work, then it's only because the connections are pooled, and you happen to get the same connection the second time. 如果您尝试使用新连接进行连接并且似乎可以正常工作,那仅仅是因为连接已被池化,并且您碰巧第二次获得了相同的连接。 When you start to use this with more than one single user, it will fail.
当您开始与多个用户使用此功能时,它将失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.