事務回滾之實例

ADO与Oracle9i

http://msdn.microsoft.com/zh-cn/library/ms971506.aspx

 

 

1. 主外鍵約束
    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
        '/// 新增一個用戶
        '/// 添加資料到user表,
        '/// 同時也必須添加到deptuser表,因為user有部門,需建立dept與user的關係。
        Dim connstr As String = System.Configuration.ConfigurationManager.ConnectionStrings("Test").ToString()
        Dim dbHelper As New DBUtility.DatabaseHelper(connstr, DBUtility.Providers.SqlServer)
        Dim strSql As String
        Try
            dbHelper.BeginTransaction()
            strSql = "insert into emp(emp_no,emp_name) values('08054495','tom')"
            dbHelper.ExecuteNonQuery(strSql, DBUtility.ConnectionState.KeepOpen)


            strSql = "insert into deptuser(keyid,empno,deptid) values(1,'08054495','666')"
            dbHelper.ExecuteNonQuery(strSql, DBUtility.ConnectionState.KeepOpen)
            dbHelper.CommitTransaction()
        Catch ex As Exception
            dbHelper.RollbackTransaction()
            Throw ex
        End Try
    End Sub

2. 批量update約束
    Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        Dim dbHelper As New DBUtility.DatabaseHelper
        Dim chkExport As CheckBox
        '遍歷對象
        '一次修改多筆記錄,若有一筆失敗,則所有的都回滾,恢復到原來的狀態。
        Try
            dbHelper.BeginTransaction()
            For Each oGridViewRow As GridViewRow In Me.GridView1.Rows
                chkExport = CType(oGridViewRow.FindControl("chkExport"), CheckBox)
                Dim lblKeyId As Label = CType(oGridViewRow.FindControl("lblKeyID"), Label)
                If chkExport.Checked = True Then
                    Dim _strSql As String = " UPDATE  xxfqa_test SET ENABLE_FLAG='n' WHERE ID=" & lblKeyId.Text.Trim()
                    dbHelper.ExecuteNonQuery(_strSql, Data.CommandType.Text, DBUtility.ConnectionState.KeepOpen)
                End If
            Next
            dbHelper.CommitTransaction()
        Catch ex As Exception
            dbHelper.RollbackTransaction()
            Throw
        End Try
        LoadData()
    End Sub

 

posted @ 2010-08-10 17:08  yellowwood  阅读(201)  评论(0编辑  收藏  举报
Never Give UP