gpt4 book ai didi

c# - MySql Last_Insert_Id() 的并发问题... (C#)

转载 作者:行者123 更新时间:2023-11-29 09:17:30 25 4
gpt4 key购买 nike

我不太确定为什么以下控制台应用程序没有产生last_insert_id() 的预期行为。我读过,last_insert_id() 返回特定连接的最后一个 auto_incremented 值,但在这段代码中,两个连接返回相同的结果。有人可以解释一下我哪里出了问题吗?

    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();
}

我知道这种情况不会发生,因为顶部连接字符串中的池化,因为我尝试在没有该字符串部分的情况下运行程序,并且我仍然得到相同的结果(即命令 1 和命令 2为last_insert_id()显示相同的值。欢迎任何想法!

非常感谢,

安德鲁

最佳答案

看这里:

command1.Connection = conn1;
command2.Connection = conn1;

您对这两个命令使用相同的连接。

关于c# - MySql Last_Insert_Id() 的并发问题... (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3623099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com