是否可以做这样的事情:
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Transactions
Public Class Form1
Private _ConString As String
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim objDR As SqlDataReader
Dim objCommand As SqlCommand, objCommand2 As SqlCommand
Dim objCon As SqlConnection
Dim objCon2 As SqlConnection
Dim id As Integer
Try
_ConString = "Data Source=IANSCOMPUTER;Initial Catalog=AdventureWorks2008R2;Integrated Security=True;MultipleActiveResultSets=true"
objCon = New SqlConnection(_ConString)
objCommand = New SqlCommand("SELECT * FROM PERSON.PERSON WHERE BusinessEntityID<=10")
objCommand2 = New SqlCommand()
objCommand.Connection = objCon
objCommand2.Connection = objCon
objCon.Open()
objDR = objCommand.ExecuteReader(ConnectionState.Closed)
Do While objDR.Read
Using scope As New TransactionScope
objCon2 = New SqlConnection(_ConString)
objCon2.Open()
Using objCon2
objCommand2.CommandText = "UPDATE Person.Person SET middlename = @middlename WHERE " & _
" Person.BusinessEntityID = @ID "
objCommand2.Parameters.AddWithValue("@middlename", objDR("BusinessEntityID") + 1)
objCommand2.Parameters.AddWithValue("@ID", objDR("BusinessEntityID"))
objCommand2.ExecuteNonQuery()
objCommand2.Parameters.Clear()
End Using
End Using
Loop
objDR.Close() 'line 16
Catch ex As Exception
Throw
Finally
End Try
End Sub
End Class
在上面的代码中,为每个循环创建了Transaction。我想这样做的原因是因为表被锁定直到while循环结束。上面代码的问题是忽略了事务的创建。
答案 0 :(得分:0)
1,您不需要使用2个不同的SqlCommands变量。 第二次尝试更改&#34; objDR = objCommand.ExecuteReader(ConnectionState.Closed)&#34;对此&#34; objDR = objCommand.ExecuteReader()&#34; 第3次尝试在while循环之前使用范围