`
wangdeshui
  • 浏览: 247657 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

ADO.NET使用事务出错的解决(MSDTC)

阅读更多

原因一:没有打开MSDTC服务

步骤:

  • Componet Services-->右击My Computer--->Start MSDTC
  • Componet Services-->右击My Computer-->属性--->MSDTC-->安全配置--->勾选上我红线标注的部分。

image

 

image

原因二: 防火墙阻止

解决方法,添加135端口到Exception

image

原因三:使用了多个连接

   1: using (TransactionScope ts = new TransactionScope())
   2: {
   3:   //...
   4:   ts.complete();
   5: }

TransactionScope不允许一个事务里有多个连接,解决办法是我们加个基础类,让所有的都是用同一个连接

   1: public class BaseDataAccess
   2: {
   3:     private SqlConnection mSqlconnection;
   4:     protected SqlConnection sqlConnection
   5:     {
   6:       get
   7:       {
   8:         if (mSqlconnection == null) mSqlconnection = new SqlConnection(SqlHelper.mConnectionString);
   9:         return mSqlconnection;
  10:       }
  11:     }
  12:  }
但是这里面需要注意的是,假如我们在一组事务里如果打开多个SqlDataReader,就会出错,解决办法:

  ADO.NET 2.的一个新特征多数据结果集(Multiple Active Result Sets,简称MARS)-它允许在单个连接上执行多重的数据库查询或存储过程。这样的结果是,你能够在单个连接上得到和管理多个、仅向前引用的、只读的结果集。目前实现这个功能的数据库只有Sql Server 2005。所以当我们针对Sql Sever 2005的时候,需要重新审视DataReader对象的使用。使用SqlServer 2005,可以在一个Command对象上同时打开多个DataReader,节约数据库联接所耗费的服务器资源,在实际开发中普遍存在的一种典型的从数据库中读写数据的情形是,你可以使用多重连接而现在只用一个连接就足够了。例如,如果你有一些来自于几个表中的数据-它们不能被联结到一个查询中,那么你就会有多重的连接-每个连接都有一个与之相关连的命令用于读取数据。同样,如果你正在向一个表写数据,那么你需要另外一个连接或连接集合-如果有多个表要被更新的话。

例如下面的代码

             

   1: //MultipleActiveResultSets=true打开联接
   2:             string connstr = "server=(local);database=northwind;integrated security=true;MultipleActiveResultSets=true";
   3:             SqlConnection conn = new SqlConnection(connstr);
   4:             conn.Open();
   5:             SqlCommand cmd1 = new SqlCommand("select * from customers", conn);
   6:             SqlCommand cmd2 = new SqlCommand("select * from orders", conn);
   7:             SqlDataReader rdr1 = cmd1.ExecuteReader();
   8:            // next statement causes an error prior to SQL Server 2005
   9:             SqlDataReader rdr2 = cmd2.ExecuteReader();
  10:            // now you can reader from rdr1 and rdr2 at the same time.
  11:             conn.Close();

王德水 祝你编程愉快

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics