【问题标题】:ADO.NET TransactionsADO.NET 事务
【发布时间】:2016-06-21 23:20:02
【问题描述】:

使用 ADO.net,如果我填充数据适配器而不隐式执行 BeginTransaction,是否会发生“事务”?如果不是,那么默认的隔离级别是多少?

【问题讨论】:

    标签: ado.net


    【解决方案1】:

    DataAdapter 没有隐含事务。

    【讨论】:

      【解决方案2】:

      要在数据适配器上运行事务,只需使用 TransactionScope。

      using (var ts = new TransactionScope())
      {
         // do your data adapter related code
         // ...
      
      
         ts.Complete();
      }
      

      使用 TransactionScope 时,您也可以指定 IsolationLevel(例如 Serializable)。 TransactionScope 的默认隔离级别是 Serializable。

      【讨论】:

        【解决方案3】:

        您需要显式创建事务。除了 TransactionScope,您还可以使用SqlTransaction

        例如:

                    var connString = "Data Source=(local);Integrated security=SSPI; Initial Catalog=Northwind";
                    var sql = "SELECT * FROM Orders";
        
                    using (var conn = new SqlConnection(connString))
                    {
                        conn.Open();
                        var da = new SqlDataAdapter(sql, conn);
                        var ds = new DataSet();
        
                        // load  data from the data source into the DataSet
                        da.Fill(ds, "Orders");
        
                        // start the transaction
                        SqlTransaction tran = conn.BeginTransaction();
        
                        // associate transaction with the data adapter command objects
                        da.DeleteCommand.Transaction = tran;
                        da.InsertCommand.Transaction = tran;
                        da.UpdateCommand.Transaction = tran;
        
                        // modify the data in the DataSet
                        // submit changes, commit or rollback, and close the connection
        
                        try
                        {
                            da.Update(ds, "Orders");
                            // commit if successful
                            tran.Commit();
                        }
                        catch (Exception)
                        {
                            tran.Rollback();
                        }
                    }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多