日期:2014-05-19  浏览次数:20941 次

请教winform中事物处理!(送分题目)
在winform程序中,要同时执行两条SQL更新语句,怎么用.NET中的事物处理来解决?给出详细的代码实例就送分,谢谢!

------解决方案--------------------
using (TransactionScope transScope = new TransactionScope())
{
string sql= "update a set b=1 ";
excutesql(sql);
transScope.Complete();
}
------解决方案--------------------
可以两种方式:

1、在SQL里构造事务
string myTran = "begin Tran T1 update table1 ... update table2 ...commit Tran T1 ";

2、c#里控制事务

string myCon = "Data Source=localhost;Initial Catalog=Northwind;uid=sa;pwd= ";
SqlConnection myConnection = new SqlConnection(myCon);
myConnection.Open();

SqlTransaction myTrans = myConnection.BeginTransaction();
SqlCommand myCommand = myConnection.CreateCommand();
myCommand.Transaction = myTrans;

myCommand.CommandText = "Insert into ... ";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "Insert into ... ";
myCommand.ExecuteNonQuery();
myTrans.Commit();

PS:楼上的方法更简洁,但2.0里才支持TransactionScope;