0

Got a question and hopefully i can learn something new from here.

I have this code.

Using Con=Openconnetion()
    'Declare MysqlCommand Object
    Dim Cmd as mysqlcommand 

    'Create new instance of mysql command object
    Cmd = New MysqlCommand

    'Inserting Data to TableHead
    Cmd.CommandText = "Insert Into TableHead(doc_no,in_date) values('A','2014-01-01')"
    Cmd.CommandType = CommandType.Text
    Cmd.Connection = Con
    Dim Result As Integer = Cmd.ExecuteNonQuery
    If Result > 0 Then

        'Create new instance of mysql command object
        Cmd = New MysqlCommand

        'If Insertion to TableHead Successfully, Then perform insertion to TableBody
        Cmd.CommandText = "Insert into TableBody(doc_no,item_no,price) values ('A','001','1000')"
        Cmd.CommandType = CommandType.Text
        Cmd.Connection = Con
        Dim Result1 as Integer = Cmd.ExecuteNonQuery
        If Result1 > 0 Then
            MsgBox ("Success")
        Else
            MsgBox ("Failed")

            'Create new instance of mysql command object
            Cmd = New MysqlCommand

            'If Insertion to TableBody Failed, Then Delete The Data From TableHead From Above Query
            Cmd.CommandText = "Delete From TableHead Where doc_no='A'"
            Cmd.CommandType = CommandType.Text
            Cmd.Connection = Con
            Cmd.ExecuteNonQuery
        End If
    End If
End Using

So, is there any simplified way to do it which when the insertion of the TableBody return a false status, it won't process the query to TableHead, so i don't need to the 3rd query to delete the data from TableHead.

Joseph Goh
  • 689
  • 5
  • 16
  • 38
  • Probably a [Transaction](http://msdn.microsoft.com/en-us/library/86773566(v=vs.110).aspx) or [TransactionScope](http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx) will do? If the result <=0 rollback. – HengChin Jul 17 '14 at 03:31
  • http://stackoverflow.com/questions/3321006/mysql-transactions-in-asp-net – HengChin Jul 17 '14 at 03:38
  • Yes, starting a new transaction with your command and rolling it back if Result1 fails (or an exception occurs) is the way forward here. – yu_ominae Jul 17 '14 at 08:33

0 Answers0