c# - 取消数据库中的上次更新

标签 c# mysql asp.net vb.net winforms

我有一个主表和一个通过引用master_gid与之关联的详细表,我必须在主表中插入摘要,在详细表中插入详细信息。一切正常。我正在关注场景:

  1. 插入主表
  2. 如果主表插入成功则插入明细表
  3. 如果明细表插入失败,则从主表中删除引用字段

这次一切都很顺利。

更新的情况下,我遵循相同的场景,但在详细表插入失败的情况下面临问题。如果detail_table插入失败,我如何撤消(使用查询)主表中的最后更新。 我使用 Imports System.Data.Odbc 连接到 mysql

最佳答案

这是来自 msdn 的关于 using transaction 的示例

Public Sub ExecuteTransaction(ByVal connectionString As String)

Using connection As New OdbcConnection(connectionString)
    Dim command As New OdbcCommand()
    Dim transaction As OdbcTransaction

    ' Set the Connection to the new OdbcConnection.
    command.Connection = connection

    ' Open the connection and execute the transaction. 
    Try
        connection.Open()

        ' Start a local transaction.
        transaction = connection.BeginTransaction()

        ' Assign transaction object for a pending local transaction.
        command.Connection = connection
        command.Transaction = transaction

        ' Execute the commands.
        command.CommandText = _
            "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
        command.ExecuteNonQuery()
        command.CommandText = _
            "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
        command.ExecuteNonQuery()

        ' Commit the transaction.
        transaction.Commit()
        Console.WriteLine("Both records are written to database.")

    Catch ex As Exception
        Console.WriteLine(ex.Message)
        ' Try to rollback the transaction 
        Try
            transaction.Rollback()

        Catch 
            ' Do nothing here; transaction is not active. 
        End Try 
    End Try 
    ' The connection is automatically closed when the 
    ' code exits the Using block. 
End Using 

结束子

关于c# - 取消数据库中的上次更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27716228/

相关文章:

asp.net - 使用 FindControl : Accessing Controls in a Formview

mysql - 如何在 MYSQL 中匹配编码的变音符?

css - 如何通过 Asp.net 捆绑在打印页面上使用 Bootstrap 样式

c# - 将 C# WCF 应用程序转换为 Visual Basic

c# - 错误 OnModelCreating (ModelBuilder)' : no suitable method found to override

c# - 错误 : a certificate chain processed, 但在根错误 .Net Framework 4.7 中终止

c# - 使用 Postman 将 GUID 列表发布到 MVC 5 Controller

mysql - kohana框架中如何进行原始查询

mysql - 以相反的方式合并

asp.net - 出现错误 "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."