保存然后在vb.net中编辑事务后出错

时间:2012-09-13 04:03:44

标签: vb.net sql-server-2008 transactions dataset dataadapter

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

  

当分配给命令的连接处于挂起的本地事务中时,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

1 个答案:

答案 0 :(得分:1)

您需要为SqlDataAdapter的InsertCommandUpdateCommandDeleteCommand对象设置Transaction对象引用,因为您正在调用Update方法。

MSDN参考文档 - Using Transactions with a 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