1Public Sub RunTransaction(myConnString As String)
2Dim myConnection As New MySqlConnection(myConnString)
3myConnection.Open()
4
5Dim myCommand As MySqlCommand = myConnection.CreateCommand()
6Dim myTrans As MySqlTransaction
7
8' Start a local transaction
9myTrans = myConnection.BeginTransaction()
10' Must assign both transaction object and connection
11' to Command object for a pending local transaction
12myCommand.Connection = myConnection
13myCommand.Transaction = myTrans
14
15Try
16myCommand.CommandText = "Insert into Test (id, desc) VALUES (100, 'Description')"
17myCommand.ExecuteNonQuery()
18myCommand.CommandText = "Insert into Test (id, desc) VALUES (101, 'Description')"
19myCommand.ExecuteNonQuery()
20myTrans.Commit()
21Console.WriteLine("Both records are written to database.")
22Catch e As Exception
23Try
24myTrans.Rollback()
25Catch ex As MySqlException
26If Not myTrans.Connection Is Nothing Then
27Console.WriteLine("An exception of type " + ex.GetType().ToString() + _
28" was encountered while attempting to roll back the transaction.")
29End If
30End Try
31
32Console.WriteLine("An exception of type " + e.GetType().ToString() + _
33"was encountered while inserting the data.")
34Console.WriteLine("Neither record was written to database.")
35Finally
36myConnection.Close()
37End Try
38End Sub