数据库回滚操作

本文详细介绍了如何使用事务处理来确保数据库操作的原子性和一致性,特别是在编辑员工信息时。通过示例代码展示了如何在.NET环境下,利用SqlConnection和SqlTransaction进行数据库的增删改查操作,并在遇到异常时回滚事务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/// ///事务 ///

internal SqlTransaction Transaction { get; set; }

public string EditEmployee(OrgEmployee employee, Guid departmentGuid, Guid companyGuid, bool isPIC)

{

SqlPlus plus = new SqlPlus();

string result = string.Empty;

using (SqlConnection conn = plus.GetConnection())

{

conn.Open();

this.Transaction = conn.BeginTransaction();//开启事物操作

try {

this.EditEmployee(employee);

this.EditEmp2Dept(employee.EmployeeGuid, departmentGuid, companyGuid, isPIC);

this.Transaction.Commit();

}

catch (Exception ex)

{

result = ex.Message; Transaction.Rollback(); conn.Close();

}

}

return result;

}

private void EditEmp2Dept(Guid employeeGuid, Guid departmentGuid, Guid companyGuid, bool isPIC)

{

SqlParameter[] prams =

{

Database.MakeInParam("@EmployeeGuid", System.Data.SqlDbType.UniqueIdentifier, 16, employeeGuid), Database.MakeInParam("@DepartmentGuid", System.Data.SqlDbType.UniqueIdentifier, 16, departmentGuid), Database.MakeInParam("@CompanyGuid", System.Data.SqlDbType.UniqueIdentifier, 16, companyGuid),

Database.MakeInParam("@IsPIC", System.Data.SqlDbType.Bit, 1, isPIC)

};

if (Transaction == null)

{

new SqlPlus().ExecuteNonQuery(CommandType.StoredProcedure, "up_Emp2DeptEdit", prams);

}

else

{

new SqlPlus().ExecuteNonQuery(Transaction, CommandType.StoredProcedure, "up_Emp2DeptEdit", prams);

}

}

  public int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

 /// <summary>
        /// 执行SQL命令
        /// </summary>
        private void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {

            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            cmd.CommandTimeout = 120;

            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

转载于:https://www.cnblogs.com/GreenGrass/archive/2012/12/06/2804930.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值