SQL数据库的事物处理
昨天面试中, 被问到数据库的事物处理时,本人不太了解。
应用事物,是为了保证一整套逻辑中涉及数据库操作的数据完整性。
using System;
using System.Collections.Generic;
using System.Text;
using System.EnterpriseServices;
namespace TranScope
{
public class ESTransactionScope : IDisposable
{
public void Dispose()
{
if(!this.Consistent)
{
ContextUtil.SetAbort();
}
ServiceDomain.Leave();
}
public void Complete()
{
this.Consistent = true;
}
public ESTransactionScope()
{
EnterTxContext(TransactionOption.Required);
}
public ESTransactionScope(TransactionOption txOption)
{
EnterTxContext(txOption);
}
private void EnterTxContext(TransactionOption txOption)
{
ServiceConfig config = new ServiceConfig();
config.Transaction = txOption;
ServiceDomain.Enter(config);
}
private bool Consistent = false;
}
}
调用的就可以这样来了:
using (TranScope t = new TranScope ())//标明事务范围
{
try
{
//这里放一系列的逻辑操作
User.Add(user_info)// 插入操作
SysPara.Update()//更新操作
Server10.AddUser(user_info) //将数据写到另一台服务器
Logger.Add(LogInfo);// 日志记录
t.Complete();
}
catch
{
Fun.Alert("操作失败!");
}
}
如果出错的话本服务器和另一台服务器的数据都会执行回滚操作,除非t.Complete()方法成功执行
在SQL SERVER里调用分布式事物可能要方便点,可以这么用
SqlConnection myConnection = new SqlConnection("Data Source=.;Initial Catalog=TEST;Integrated Security=SSPI;");
myConnection.Open();
// 启动一个事务
SqlTransaction myTrans = myConnection.BeginTransaction();
// 为事务创建一个命令
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = "Insert into T1(ID, NAME) VALUES (103, 'XO')";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "Insert into T2(ID, NAME) VALUES (101, 'NB')";
myCommand.ExecuteNonQuery();
myTrans.Commit();
Console.WriteLine("OK.");
}
catch (Exception ex)
{
myTrans.Rollback();
Console.WriteLine(ex.ToString());
}
finally
{
myConnection.Close();
}
这么用就不太好了,如果是复杂的逻辑处理,可能就很不好搞了,最好还是在事物处理时与数据连接分离开来,只需要把想要的操作方法放到事物块里就好了。
http://www.cnblogs.com/peaceli/archive/2008/04/22/1163011.html
浙公网安备 33010602011771号