MySql Last Insert ID, Connector .net

后端 未结 6 2092
广开言路
广开言路 2020-12-01 16:22

I\'m using the MySql Connector .net, and I need to get the insert id generated by the last query. Now, I assume the return value of MySqlHelper.ExecuteNonQuery

6条回答
  •  再見小時候
    2020-12-01 17:02

    I had the same problem, and after some testing, I found out that the problem seem to be the connection method; you are using a connection string.

    This is of course to make use of the automatic connection pool reuse, but in this case it gave me trouble.

    The final solution for me is to create a new connection, execute the insert query, and then execute the last_insert_id(). On the same connection.

    Without using the same connection, last_insert_id() might return anything, I don't know why, but guess it looses track of things as it can be different connections.

    Example:

    MySqlConnection connection = new MySqlConnection(ConnectionString);
    connection.Open();
    
    int res = MySqlHelper.ExecuteNonQuery(
        connection,
        "INSERT INTO games (col1,col2) VALUES (1,2);");
    
    object ores = MySqlHelper.ExecuteScalar(
    connection,
    "SELECT LAST_INSERT_ID();");
    
    if (ores != null)
    {
      // Odd, I got ulong here.
      ulong qkwl = (ulong)ores;
      int Id = (int)qkwl;
    }
    

    I hope this helps someone!

提交回复
热议问题