您的位置:首页 > 数据库

数据库回滚操作

2012-12-06 14:29 471 查看
/// ///事务 ///

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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: