MySql Last Insert ID, Connector .net

后端 未结 6 2097
广开言路
广开言路 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 16:55

    I know this is an old post, but I have been facing the same issue as Snorvarg. Using MySqlHelper, and using a connection string instead of a Connection object (to allow MySqlHelper to use connection pooling), SELECT LAST_INSERT_ID() would often give me the ID of the previous query that was executed, or other times it would return zero. I would then have to call SELECT LAST_INSERT_ID() a second time to get the correct ID.

    My solution was to encapsulate everything between the query that's being executed, and the calling of SELECT LAST_INSERT_ID() in a TransactionScope. This forces MySqlHelper to stick to one connection instead of opening two separate connections.

    So:

    string sql = "INSERT INTO games (col1,col2) VALUES (1,2);");
    string connectionString = "some connection string";
    
    using (TransactionScope scope = new TransactionScope)
    {
        int rowsAffected = MySqlHelper.ExecuteNonQuery(connectionString, sql);    
        object id = MySqlHelper.ExecuteScalar(connectionString, "SELECT LAST_INSERT_ID();");
        scope.Complete();
    }
    

提交回复
热议问题