在C#事务模式中,怎样在条件不满足时,并不是出错时,回滚并抛出错误,代码如下 5
publicvoidModifyEmail(intUserId,stringNewEmail,stringOldEmail){stringEmail="";stringc...
public void ModifyEmail(int UserId, string NewEmail,string OldEmail)
{
string Email = "";
string cmdText = "select Email from Users TABLOCKX where UserId="+UserId;
SqlConnection conn = new SqlConnection(Connection.ConnString);
SqlCommand cmd = new SqlCommand(cmdText, conn);
conn.Open();
SqlTransaction tr = conn.BeginTransaction();
cmd.Transaction = tr;
try
{
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Email = dr["Email"].ToString();
}
dr.Close();
if (Email == OldEmail)
{
cmd.CommandText = "Update users Set Email='" + NewEmail + "' Where UserId=" + UserId;
cmd.ExecuteNonQuery();
}
else
{
//要求此处能抛出错误,或中止事务并回滚(此处能中止事务吗?)
}
tr.Commit();
}
catch(Exception ex)
{
tr.Rollback();
throw ex;
}
finally { conn.Close(); }
} 展开
{
string Email = "";
string cmdText = "select Email from Users TABLOCKX where UserId="+UserId;
SqlConnection conn = new SqlConnection(Connection.ConnString);
SqlCommand cmd = new SqlCommand(cmdText, conn);
conn.Open();
SqlTransaction tr = conn.BeginTransaction();
cmd.Transaction = tr;
try
{
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Email = dr["Email"].ToString();
}
dr.Close();
if (Email == OldEmail)
{
cmd.CommandText = "Update users Set Email='" + NewEmail + "' Where UserId=" + UserId;
cmd.ExecuteNonQuery();
}
else
{
//要求此处能抛出错误,或中止事务并回滚(此处能中止事务吗?)
}
tr.Commit();
}
catch(Exception ex)
{
tr.Rollback();
throw ex;
}
finally { conn.Close(); }
} 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询