简体   繁体   中英

last_insert_id with multiple threads

I'm writing an application in C# that basically consists of two threads. Thread 1 gets data and puts it into a database, thread 2 takes that data does some additional operations. Will I run into problems with last_insert_id, like getting an insert id in the first thread from an insert that was done in the second thread? I am using the connector .net and primarily use the MySqlHelper with the connection string as a parameter.

Is last_insert_id safe to use in this case or would I be better off rethinking my approach, like creating two separate applications for these to tasks?

Also, I can't do everything in one thread. Each thread runs periodically and takes a different amount to complete. The first thread has to be able to insert data while the second thread performs its operations.

last_insert_id() is reliable on a PER CONNECTION basis. If your threads are sharing the same MySQL connection and doing inserts, then it's undefined as to what ID you'll be retrieving.

If you're not running too many threads, you might be better off having the individual threads open their own MySQL connections, and then you'd be able to use last_insert_id() without issue.

You will get true results by writing the code in below mentioned way...

Sample C# Code

using (SqlConnection con = new SqlConnection("Your Connection String"))
{
    using (SqlCommand cmd = new SqlCommand("Your Stored Procedure Name", con))
    {
        SqlParameter param = new SqlParameter();
        param.ParameterName = "Parameter Name";
        param.Value = "Value";
        param.SqlDbType = SqlDbType.VarChar;
        param.Direction = ParameterDirection.Input;
        cmd.Parameters.Add(param);
        using (IDataReader DR = cmd.ExecuteReader())
        {
            if (DR.Read())
            {
            }
        }
    }
}

Sample Stored Procedure

Create Proc ABC AS

SET NOCOUNT ON
SET XACT_ABORT ON
Begin Try
    Begin Tran
        //Insert Statement
        Select Scope_Identity()
    End Tran
End Try

Begin Catch
    Rollback Tran
End Catch

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