1

使用我的代码成功保存交易后...我编辑交易然后保存...然后我想出了这个错误消息:

当分配给命令的连接处于挂起的本地事务中时,ExecuteNonQuery 要求该命令具有事务。该命令的 Transaction 属性尚未初始化。

这是我的代码:

Try
  sqlTrans = sqlCon_.BeginTransaction(IsolationLevel.RepeatableRead)
  sSQLAdapter_.UpdateBatchSize = 30
  sCommand_ = DirectCast(sSQLAdapter_.SelectCommand, SqlCommand)
  sCommand_.Connection = sqlCon_ 
  sCommand_.Transaction = sqlTrans 
  sSQLAdapter.SelectCommand.Transaction = sqlTrans

  sSQLAdapter_.Update(sDataSet.Tables(0))

  sqlTrans.Commit()
  sqlCon_.Close()

Catch ex As Exception
  sqlTrans.Rollback()
Finally
   sSQLAdapter.SelectCommand.Connection.Close()
   sSQLAdapter.SelectCommand.Connection = Nothing
   sSQLAdapter.SelectCommand.Transaction = Nothing
   sSQLAdapter.SelectCommand.CommandText = ""
   sSQLAdapter.SelectCommand.Dispose()

   sqlTrans.Dispose()
   sqlCon_.Close()
   sqlCon_.Dispose()
End Try
4

1 回答 1

1

您需要为SqlDataAdapter和对象设置 Transaction 对象引用InsertCommand,因为您正在调用方法。UpdateCommandDeleteCommandUpdate

MSDN 参考文档 -使用带有 DataAdapter 的事务

样本 :

Using Cn As New SqlConnection(CnStr)
 Cn.Open()
 Using Trans As SqlTransaction = Cn.BeginTransaction
   Dim Adp As New SqlDataAdapter(selectQuery, Cn)
   Adp.SelectCommand.Transaction = Trans

   Dim cmb As New SqlCommandBuilder(Adp)
   Adp.DeleteCommand = cmb.GetDeleteCommand()
   Adp.InsertCommand = cmb.GetInsertCommand()
   Adp.UpdateCommand = cmb.GetUpdateCommand()

   Adp.InsertCommand.Transaction = Trans
   Adp.DeleteCommand.Transaction = Trans
   Adp.UpdateCommand.Transaction = Trans

   Dim dt As New DataTable
   Adp.Fill(dt)
   /* ------------- 

    Perform insert/delete/update on DataSet or DataTable 
    -------------- */ 
   Adp.Update(dt)
   Trans.Commit()
  End Using
 Cn.Close()
End Using
于 2012-09-13T04:13:31.620 回答