I am having a problem with 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! 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?
here is my code:
#region Pri开发者_如何转开发vate 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.
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 [
LAST_INSERT_ID
] to a given client is the firstAUTO_INCREMENT
value generated for most recent statement affecting anAUTO_INCREMENT
column by that client. This value cannot be affected by other clients, even if they generateAUTO_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.
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.
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.
精彩评论