netnr 2016-04-08
#region 跨数据库 事务操作

public bool ExecTransactionScope(System.Collections.Generic.List<TransactionScopeModel> list)
{
    bool result = true;

    //保存每条事务对象、结果
    System.Collections.Generic.Dictionary<SqlTransaction, int> dicTrans = new System.Collections.Generic.Dictionary<SqlTransaction, int>();

    //保存每条事务的Conn、Cmd对象
    System.Collections.Generic.Dictionary<SqlConnection, SqlCommand> diccc = new System.Collections.Generic.Dictionary<SqlConnection, SqlCommand>();

    foreach (TransactionScopeModel tsm in list)
    {
        try
        {
            SqlConnection conn = new SqlConnection(tsm.conn);
            conn.Open();
            SqlTransaction trans = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.Transaction = trans;

            cmd.CommandText = tsm.cmdTxt;
            if (tsm.param != null)
            {
                foreach (SqlParameter p in tsm.param)
                {
                    cmd.Parameters.Add(p);
                }
            }
            int rows = cmd.ExecuteNonQuery();

            result = rows > 0 ? true : result;

            dicTrans.Add(trans, rows);//保存执行结果 事务对象
            diccc.Add(conn, cmd);//保存连接对象、操作数据库对象
        }
        catch (Exception)
        {
            result = false;
            break;
        }
    }

    //遍历执行的结果
    foreach (int rows in dicTrans.Values)
    {
        if (rows > 0)
        {
            continue;
        }
        else
        {
            //某条结果执行失败
            result = false;
            break;
        }
    }
    if (result)
    {
        //遍历事务 并依次提交
        foreach (SqlTransaction trans in dicTrans.Keys)
        {
            trans.Commit();
        }
    }
    else
    {
        //回滚
        foreach (SqlTransaction trans in dicTrans.Keys)
        {
            trans.Rollback();
        }
    }
    //释放
    foreach (SqlConnection conn in diccc.Keys)
    {
        conn.Close();
    }
    foreach (SqlCommand cmd in diccc.Values)
    {
        cmd.Dispose();
    }

    return result;
}

/// <summary>
/// 跨数据库事务操作实体对象
/// </summary>
public class TransactionScopeModel
{
    /// <summary>
    /// 数据库连接字符串
    /// </summary>
    public string conn { get; set; }

    /// <summary>
    /// 执行SQL
    /// </summary>
    public string cmdTxt { get; set; }

    /// <summary>
    /// 参数组
    /// </summary>
    public SqlParameter[] param { get; set; }
}

#endregion
登录写评论