Monday, February 8, 2010

ADO.NET Code showing Dataset storing multiple tables

Declare and initialize database connection object with appropriate connection string.
Create a DataAdapter and a Dataset object.
Using fill method of the DataAdapter object, load the data into the Dataset Object.
Change the adapter's SELECT command.
Create the EmpDetail table.
Add both tables to a single dataset.
Display the data using data binding feature of controls like Datagrid or Datalist.

Dim m_adptEmp As SqlDataAdapter

Private Sub Page_Load(ByVal sender As System.Object, _
ByValeAsSystem.EventArgs)HandlesMyBase.Load
DimEmpConnAsNewSqlConnection_
("server=(local);database=Employees;Trusted_Connection=yes")
m_adptEmp = New SqlDataAdapter("select * from Emp", EmpConn)
Dim dsEmp As New DataSet
m_adptEmp.Fill(dsEmp, "Emp")
adptEmp.SelectCommand.CommandText = "SELECT * FROM EmpDetail"
Dim EmpDetail As New DataTable("EmpDetail")
adptDB.Fill(EmpDetail)
dsBoth.Tables.Add(Emp)
dsBoth.Tables.Add(EmpDetail)
DataGrid1.DataSource = dsEmp.Tables("Emp").DefaultView
DataGrid1.DataBind()
End Sub

ADO.NET Code executing stored procedure

Code showing how to fetch data using Stored Procedure.

Imports System
Imports System.Data
Imports System.Data.SqlClient

Private Function FillForm()
Dim myConn As New SqlConnection()
Dim Parm As New SqlParameter()
Dim dr As SqlDataReader
myConn.ConnectionString = "data source=(local);initial catalog=Jobs;integrated security _
=SSPI;persist security info=False;workstation id=XYZ;packet size=4096"
myConn.Open()
Dim cmd As SqlCommand = New SqlCommand("Select_Employer", myConn)
cmd.CommandType = CommandType.StoredProcedure
Parm = cmd.Parameters.Add("@EmployerId", SqlDbType.Int, 9)
Parm.Value = 1
dr = cmd.ExecuteReader()
If (dr.Read = True) Then
txtName.Text = dr("UserName")
end if
dr.Close()
dr = Nothing
cmd.Connection.Close()
myConn.Close()
End Function

ADO.NET transaction Processing

Steps to use transaction object

Open a database connection.
Create the transaction object using BeginTransaction method of connection object.
Create command object by using transaction object as the parameter.
Execute the commands and check for the error.
If no error, commit the changes to the database or restore the database state.
Close the connection.

The transaction object handles concurrency issue using IsolationLevel settings. The settings can be

ReadUncommitted
Chaos
ReadCommitted
RepeatableRead
Serializable

No comments:

Post a Comment