請參閱下面的代碼:儘管scope.complete被註釋掉的TransactionScope - 承諾在每次迭代
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
三個update語句執行。我相信這是因爲連接在TransactionScope之外打開。
如果我想要循環通過一個萬人發出這些更新則有兩種選擇:
1)請所有更新,並在年底 2更改提交到數據庫)提交每個循環的變化 - 然後我將不得不爲每個循環打開一個新的連接。
開發者是否總是選擇選項1?即作爲批次發佈更新。
可能是一個錯字,但你的更新沒有多大意義。 URN總是在末尾 – Steve 2013-04-20 15:10:30
史蒂夫,這不是一個錯字,但我可以看到它爲什麼造成混亂(因此沒有答案)。我介紹了@Steve,Visual Studio中的代碼,並且三條SQL語句分別在28,30和32行執行。由於這是一個事務,我不希望發生這種情況。你能否確認連接對象必須在transactiom內打開? – w0051977 2013-04-20 18:11:32
我從來沒有使用'TransactionScope',它有什麼好處?爲什麼不使用'Transaction'呢?我剛剛通過MSDN,並沒有得到你爲什麼使用第一個。 – Neolisk 2013-04-20 23:43:59