Transaction in vb.net
This article shows how we can achieve successful transaction maintaining consistency of records in the database.
Transaction:
Transaction is a process. A transaction can be a set of more then one process. If a transaction is a set of more then one process, then for successful completion of that transaction, it is necessary that all processes should be executed successfully in that transaction.
Let understand the transaction concept with this example.
Here in this example, I am using a set of two-process transaction. Here I am executing two commands simultaneously with transaction. With first command I am deleting a record from table and with second I am inserting a new record in the table.
Before executing the transaction, the record in the table is:
Figure 1: Here in transaction I am deleting the record where location is England and also I am inserting a record in the table.
The code for this transaction is:
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports System.Data.SqlClient
Namespace TranSactionIn.NET
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private con As SqlConnection
Private cmd1 As SqlCommand = New SqlCommand()
Private cmd2 As SqlCommand = New SqlCommand()
Private trm As SqlTransaction
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
con = New SqlConnection("Data Source=(local);Initial Catalog=Employee; Uid=sa; pwd=")
cmd1.CommandText = "delete from EmployeeRecord where Location='England'"
cmd2.CommandText = "Insert into EmployeeRecord (DeptNo,Name,DepartName,Location) values ('901','Sahib','Manager','Africa')"
cmd1.Connection = con
cmd2.Connection = con
con.Open()
trm = con.BeginTransaction()
cmd1.Transaction = trm
cmd2.Transaction = trm
cmd1.ExecuteNonQuery()
cmd2.ExecuteNonQuery()
trm.Commit()
End Sub
End Class
End Namespace
After running this code in table data we see that all records deleted where Location was England and a new record has been inserted in table. A very good example of transaction is banking money transaction.
Figure 2: After Transaction commit we can see the changed record.
NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON DOTNETHEAVEN (https://dotnetheaven.com/).