Cara Penggunaan sqlTransaction di vb.net 2008

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

Post a Comment