简体   繁体   中英

How to select last insert id without collision

I have a table:

CREATE TABLE MyTable (
  UserID BIGINT NOT NULL AUTO_INCREMENT,
  Name VARCHAR(50) NOT NULL,
  PRIMARY KEY (UserID));

Now I need to insert value and get last insert key for that value. Right now I do it like this:

using (MySqlConnection connection = new MySqlConnection(CONNECTION_STRING))
{
    connection.Open();
    string query = $"INSERT INTO MyTable VALUES('Bob');\n" +
                   $"SELECT last_insert_id();";

    MySqlCommand command = new MySqlCommand(query, connection);
    var dataReader = command.ExecuteReaderAsync();
    await dataReader;

    long id = -1;
    while (dataReader.Result.Read())
    {
        string idString = (dataReader.Result as IDataRecord)[0].ToString();
        id = long.Parse(idString);
    }

    return id;
}

But what if there will be to many queries in one time? Is it possible that 2 simultaneous commands execute INSERT query and then both return the same value via last_insert_id()? How can I make sure that last_insert_id() will return value corresponding to its INSERT inside one command?

No, last_insert_id is maintained on a per-connection basis, so if two connections are running at the same time, one won't get the other's inserted value.

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