简体   繁体   中英

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(). 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. 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()). Any ideas are welcome!

Many thanks,

Andrew

Look here:

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

You are using the same connection for both commands.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM