2010年8月3日 星期二

交易元件 TransactionScope

Private Sub TestTransactionScope()
'以下是交易元件 TransactionScope 的範例
Dim strSql As String

strSql = "INSERT INTO tb1L (F1L_id, F1L_name) " & _
"VALUES (@F1L_id, @F1L_name) "

Using Scope As New TransactionScope
Try
'注意 TransactionScope 元件是以一個連線 SqlConnection 為準
'所以盡量使用
'Using Conn As New SqlConnection(strConnection)
'End Using
'以確保會再發生錯誤時正確關閉連線
Using Conn As New SqlConnection(strConnection)
Conn.Open()

Dim RmvCMD As SqlCommand = New SqlCommand
RmvCMD.CommandType = CommandType.Text
RmvCMD.Connection = Conn

RmvCMD.CommandText = strSql

'欄位格式設定
With RmvCMD.Parameters
.Add(New SqlParameter("@F1L_id", SqlDbType.VarChar))
.Add(New SqlParameter("@F1L_name", SqlDbType.VarChar))
End With

'TEST1
RmvCMD.Parameters("@F1L_id").Value = "T900009"
RmvCMD.Parameters("@F1L_name").Value = "測試1"
RmvCMD.ExecuteNonQuery()
'以上這一段理論上是可以正常通過的

'TEST2 這裡 F1L_id 超過欄位長度 所以會錯誤
RmvCMD.Parameters("@F1L_id").Value = "T900006000000000"
RmvCMD.Parameters("@F1L_name").Value = "測試2"
RmvCMD.ExecuteNonQuery()

End Using
'--注意 End Using 一定要在 Scope.Complete() 之前
' 不然會發揮不了
' TransactionScope 的作用且也不會有錯誤提示

'交易確認
Scope.Complete()
MsgBox("交易完成!")
Catch ex As Exception
MsgBox("交易發生錯誤!" & ex.Message)
End Try
End Using
End Sub

沒有留言:

張貼留言