Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
if 3rd table i loop 2nd time and insert failed how i loop back to previous data include the tableA,tableB data need rollback.Or i just no want insert anything if i meet the error.

What I have tried:

i have 3 table that i want to insert

1st insert
VB
insert into table (A) values (A)


2nd insert after 1st insert complete
VB
insert into tableB (B) values (B)


3rd insert is loop statement
VB
For value As Integer = 0 To 5   
 insert into tableC (C) values (value)
NEXT
Posted
Updated 15-Mar-16 5:21am

1 solution

Start a transaction before you do any of the inserts. See MySQL :: MySQL 5.7 Reference Manual :: 13.3.1 START TRANSACTION, COMMIT, and ROLLBACK Syntax[^]

Wrap the entire set of inserts within a Try-Catch block and include a Rollback in the Catch block.

E.g.
VB
Dim cmd As New MySqlCommand()
Dim trn As MySqlTransaction

trn = yourConnection.BeginTransaction(IsolationLevel.ReadCommitted)
cmd.Transaction = trn

Try
   cmd.CommandText = "insert into table (A) values (A)"
   cmd.ExecuteNonQuery()
   cmd.CommandText = "insert into tableB (B) values (B)"
   cmd.ExecuteNonQuery()
   For value As Integer = 0 To 5   
      cmd.CommandText = "insert into tableC (C) values (value)"
      cmd.ExecuteNonQuery()
   NEXT

   trn.Commit()  'all values will have been inserted

Catch e As Exception

   trn.Rollback() 'no values will have been inserted

End Try

NOTE: I haven't included any code for the connection, nor proper handling of the error once the rollback has occurred (you might want to let your user know about the error).
This code is untested and is only intended to show you the principle - there may be minor errors.

You also tagged your question with storedproc so if you want to do this all within a MySQL stored procedure instead of VB have a look at the solution from wchiquito on this link[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900