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

时间:2010-09-02 00:48:16

标签: c# mysql primary-key

我不确定为什么以下控制台应用程序不会产生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()的相同值。欢迎任何想法!

非常感谢,

安德鲁

1 个答案:

答案 0 :(得分:2)

看这里:

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

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