且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在单个事务中发送多个SQL命令

更新时间:2023-11-21 20:52:52

如果在一个线程中执行多个查询,建议使用SQL事务,您可以像这样:

Its recommended to use SQL transaction in case you are executing Multiple queries in one thread , you can have it like this :

    SqlTransaction trans; 

    try
    {
        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();

        trans = connection.BeginTransaction(); 

        foreach (var commandString in sqlCommandList)
        {
            SqlCommand command = new SqlCommand(commandString, connection,trans);
            command.ExecuteNonQuery();
        }

        trans.Commit(); 
    }
    catch (Exception ex) //error occurred
    {
        trans.Rollback();
        //Handel error
    }