简体   繁体   English

具有多个线程的last_insert_id

[英]last_insert_id with multiple threads

I'm writing an application in C# that basically consists of two threads. 我正在用C#编写一个基本上由两个线程组成的应用程序。 Thread 1 gets data and puts it into a database, thread 2 takes that data does some additional operations. 线程1获取数据并将其放入数据库,线程2获取该数据执行一些附加操作。 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? 我是否会遇到last_insert_id的问题,例如从第二个线程中完成的插入中获取第一个线程中的插入ID? I am using the connector .net and primarily use the MySqlHelper with the connection string as a parameter. 我正在使用连接器.net,主要使用MySqlHelper和连接字符串作为参数。

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? 在这种情况下,last_insert_id是否可以安全使用?还是最好重新考虑自己的方法,例如为任务创建两个单独的应用程序?

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. 基于每个连接,last_insert_id()是可靠的。 If your threads are sharing the same MySQL connection and doing inserts, then it's undefined as to what ID you'll be retrieving. 如果您的线程共享相同的MySQL连接并执行插入操作,则您要获取的ID不确定。

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. 如果您没有运行太多线程,则最好让各个线程打开它们自己的MySQL连接,然后您可以使用last_insert_id()而不会出现问题。

You will get true results by writing the code in below mentioned way... 通过以下面提到的方式编写代码,您将获得真实的结果...

Sample C# Code 示例C#代码

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 创建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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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