[英]Concurrency Problem With MySql Last_Insert_Id()… (C#)
I'm not really sure why the following console application doesn't produce the expected behavior for last_insert_id(). 我不太确定为什么以下控制台应用程序不会对last_insert_id()产生预期的行为。 I've read that last_insert_id() returns the last auto_incremented value for a particular connection, but in this code, the same result is returned for both connections.
我读过last_insert_id()返回特定连接的最后一个auto_incremented值,但是在这段代码中,两个连接都返回相同的结果。 Can someone explain where I've gone wrong?
有人可以解释我哪里出问题了吗?
static void Main(string[] args)
{
string ConnectionString = "server=XXXX;database=XXXX;username=XXXX;password=XXXX;pooling=true;max pool size=100;min pool size=0";
MySqlConnection conn1 = new MySqlConnection(ConnectionString);
MySqlConnection conn2 = new MySqlConnection(ConnectionString);
MySqlCommand command1 = new MySqlCommand();
MySqlCommand command2 = new MySqlCommand();
command1.Connection = conn1;
command2.Connection = conn1;
StringBuilder createTableCommandText = new StringBuilder();
createTableCommandText.Append("Create Table TestTable (");
createTableCommandText.Append("Id INT NOT NULL AUTO_INCREMENT, ");
createTableCommandText.Append("str VARCHAR(20) NOT NULL, ");
createTableCommandText.Append("PRIMARY KEY (Id));");
StringBuilder insertCommandText = new StringBuilder();
insertCommandText.Append("INSERT INTO TestTable (str) VALUES ('what is the dilleo?');");
StringBuilder getLastInsertId = new StringBuilder();
getLastInsertId.Append("SELECT LAST_INSERT_ID();");
conn1.Open();
conn2.Open();
command1.CommandText = createTableCommandText.ToString();
command1.ExecuteNonQuery();
command1.CommandText = insertCommandText.ToString();
command2.CommandText = insertCommandText.ToString();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command1.CommandText = getLastInsertId.ToString();
Console.WriteLine("Command 1: {0}", command1.ExecuteScalar().ToString());
command2.CommandText = getLastInsertId.ToString();
Console.WriteLine("Command 2: {0}", command2.ExecuteScalar().ToString());
conn1.Close();
conn2.Close();
Console.ReadLine();
}
I know that this is not happening because of the pooling in the connection string at top, since I tried running the program without that part of the string, and I still got the same results (ie that both Command 1 and Command 2 displayed the same value for last_insert_id()). 我知道这不会发生,因为在顶部的连接字符串中存在池,因为我尝试在不包含字符串的那部分的情况下运行程序,而且我仍然得到相同的结果(即Command 1和Command 2显示相同的结果last_insert_id()的值。 Any ideas are welcome!
欢迎任何想法!
Many thanks, 非常感谢,
Andrew 安德鲁
Look here: 看这里:
command1.Connection = conn1;
command2.Connection = conn1;
You are using the same connection for both commands. 两个命令都使用相同的连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.