请看下面的代码:
Imports System.Transactions
Imports System.Data.SqlClient
Imports System.Web.Configuration
Partial Class _Default
Inherits System.Web.UI.Page
Private _ConString As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim objDR As SqlDataReader
_ConString = WebConfigurationManager.ConnectionStrings("TestConnection").ConnectionString
Dim objCon As New SqlConnection(_ConString)
Dim objCommand As New SqlCommand
objCommand.CommandText = "SELECT * FROM Person"
'Using scope As New TransactionScope()
objCon.Open()
Using scope As New TransactionScope()
objCommand.Connection = objCon
objDR = objCommand.ExecuteReader
Do While objDR.Read
Dim i As String = objDR("id2")
Dim objCommand2 As New SqlCommand
objCommand2.Connection = objCon
objCommand2.CommandText = "UPDATE Person SET URN=1 WHERE id2 = '" & i & "'"
objCommand2.ExecuteNonQuery() 'line 28
objCommand2.CommandText = "UPDATE Person SET URN=2 WHERE id2 = '" & i & "'"
objCommand2.ExecuteNonQuery() 'line 30
objCommand2.CommandText = "UPDATE Person SET URN=3 WHERE id2 = '" & i & "'"
objCommand2.ExecuteNonQuery() 'line 32
Loop
'scope.Complete() 'line 34
End Using
objDR.Close()
Catch ex As Exception
Throw
End Try
End Sub
End Class
即使 scope.complete 被注释掉了,这三个更新语句也会被执行。我相信这是因为连接是在 TransactionScope 之外打开的。
如果我想循环访问 100 万人来发布这些更新,那么有两种选择:
1)进行所有更新并在最后提交对数据库的更改 2)在每个循环上提交更改 - 然后我必须为每个循环打开一个新连接。
开发人员是否总是选择选项 1?即批量发布更新。