SoFunction
Updated on 2025-04-04

C# Implementation Database Transaction Example Sharing

        /// <summary>
/// Execute multiple SQL statements to implement database transactions.
        /// </summary>
/// <param name="SQLStringList">The hash table of the SQL statement (key is a sql statement, value is the SqlParameter[] of the statement)</param>
        private static Result<int> ExecuteSqlTransaction(params ExecuteableUnit[] executeableUnits)
        {
            using (SqlConnection connection = new SqlConnection(""))
            {
                ();
                SqlCommand command = ();
                SqlTransaction transaction = ();
                = connection;
                = transaction;
                int result = 0;
                try
                {
                    foreach(ExecuteableUnit exeUnit in executeableUnits)
                    {
                        = ;
                        if((1) > 0)
                        {
                            foreach(SqlParameter p in )
                                (p);
                        }
                        result += ();
                    }
                    ();
                }
                catch (Exception ex)
                {
                    // Attempt to roll back the transaction.
                    try
                    {
                        ();
                    }
                    catch (Exception ex2)
                    {
                        return new Result<int>()
                        {
                            Success = false, Message = , StackTrace =
                        };
                    }
                    return new Result<int>()
                    {
                        Success = false, Message = , StackTrace =
                    };
                }
                finally
                {
                    // Attempt to roll back the transaction.
                    try
                    {
                  ();
                    }
                    catch (Exception ex)
                    {
                    }
                }
                return new Result<int>()
                {
                    Success = true, data = result
                };
            }
        }