0% found this document useful (0 votes)
19 views10 pages

404 VB Chap5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views10 pages

404 VB Chap5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Unit 5:

ADO.NET
Most application requires some form of data access.
With ADO.Net we can work with database from vb.net application.
Ado.net is a part of miscrosoft ..Net framework.
The full form of ADO.Net is Active X Data Objects.

Ado.net is collection of classes,interfaces, structures and enumerated types that manage


data access from relational data stores within the .net framework.
Ado.net has the ability to separate data access mechanism, data manipulation and data
connectivity.
Ado.net allows application to read and write information in databases.
ADO.net can be used by any .net language.

Initially DAO i.e. Data Access Object was the first data access model created for local
database. Then RDO i.e.Remote Data Object and then ADO ie active data object came
into existence.
These connections were open for the application and it raises issues like database
security,network traffic and productivity.

These problems were removed by ADO.Net as it is Disconnected Data Model

ADO ADO.Net
Ado works in connected scenario Ado.net works in disconnected
scenario
Ado uses OLEDB that provides data Ado.net works with both OLEDB and
access against OLEDB provider Non-OLEDB providers
Ado holds only one result set Ado.net data set class can hold
multiple tables of data in data table
object
In Ado XML support is limited In Ado.net XML support is robust
In Ado client connection model is very In Ado.net client disconnected as soon
poor as the data is fetched or processed
data set is always disconnected.

There are two components of ADO.net through which we can access and manipulate
data.

1.Netframewok data provider


2.Dataset

CBPCC
1
1.data provider

the data provider is responsible for providing and maintaining the connection to the
database.
It is a set of classes that can be used for communicating with database and manipulating
data.
It provides fast ,forward-only,read only access to data.
The provider connects to the data source on behalf of Ado.net
The data source can be either Ms SQL Server,Oracle or OLEDB(object linking and
embedded database) data provider .
The data provider objects are seperarte for different data source i.e.for SQL ---SQL
connection is used and for access –OLEDB connection is used.
The data provider has following 4 types of object.

1.connection transaction
2.command parameter
3.data reader
4.data adapter.

Data provider
SQL Server OLEDB Oracle ODBC
System.Data.SQLClient System.data.OLEDB System.Data.OracleClient System.data.ODBC
CBPCC
2
SQL Connection OLEDB Connection Oracle Connection ODBC Connection
SQL Command OLEDB Command Oracle Command ODBC Command
SQL Data Adapter OLEDB Data Adapter Oracle Data Adapter ODBC Adapter
SQL Data Reader OLEDB Data Reader Oracle Data Reader ODBC Data Reader

1.connection object:

The connection object creates connection to the database.


It represents physical connection to a data source.
Connection object contains all the information required to open a connection to the
database.
e.g if we want to use access as data source that we have to import System.Data.OlEDB

dimcn as new OLEDBconnection


cn = new OLEDBconnection (“provider =Microsoft jet;oledb 4.0; datasource =c:\d1.mdb”)
cn.open()

properties

1.connection string:- string used to open a connection to a database


2.database:- Get the name of current database
3.datasource:-get the instance of data provider
4.state:- it returns 0 when not connected else 1 for connected. It returns state of
connection object

Methods:
Open():- it opens a connection to the database
Close():- It closes the connection

2.command object

Command object is used to execute SQL commands on database.


Command objects in ADO.Net executes SQL statements and store procedures against
data source specified in connection object.
Command object use connection object to execute query.
Command object return single value or more set of rows or no values.

Methods:
1.executenonquery
It executes the query and does not return any rows but it returns a number indicating total
number of rows affected by query
CBPCC
3
It is used for insert,update and delete statement.

2.execute reader
It returns data reader.it returns rows from database.

3.execute scalar
It returns a single value.it is used with aggregate function.it returns only first column of
first row.

3.data adapter

It is associated with command and connection object


It is used for disconnected data access. It is a bridge between dataset and data provider..
It transfer data from and to dataset and database.
It provides set of methods and properties to save data between dataset and database.
Using fill() we can retrieve data and store them in dataset.
Using update method we can store changes to the original database from dataset.

Data adapter provides 4 properties to represent database command.


1.select command
2.update command
3.insert command
4.delete command

4.Data set

Ado.net stores data locally in the client database.


Dataset is a disconnected ,in memory representation of data.
It can be considered as local copy of some portion of database.
Dataset contains collection of one or more database objects made up of rows and
columns of data.
You can fill dataset from datasource table. Tables in dataset can be identified using tables
property.
Dataset also contain primary key, foreign key ,constraints and relation information about
data in data table object.
Dataset are fully XML featured whatever operations are madeby user in the dataset , it is
stored temporarily.
After all operations are completed we can use update method to make changes in main
database from dataset.
Dataset may contain data from multiple data source. So it is not dependent on data
source. Dataset is populated with data adapter fill() method.
Properties:
1.tables:

CBPCC
4
A database collection object represents all tables in dataset. We can use either index
number or table name.
e.g datagridview1.datasource = ds.table(0)

methods.
1.clear:
Removes all data stored in the dataset by clearing all data.
2.merging:
It merges with another dataset.

5. Data reader

It is used to retrieve read only ,forward only stream of data from database ; we cant
perform any insert,update and delete operations in data reader.
We cant move to previous record in the data reader. When e want to fill controls like
combo box or data grid view then we can use data reader.

Data readers requires open connection .data reader can hold one table at a time. Data
reader can increase application performance both by retrieving data as soon as it is
available and storing only one row at a time in memory. So it reduces system overhead.
Data reader have item collection. It has read method to read next record.
Data reader can be filled by execute reader method of command object.

For e.g
Str= “select * from emp;
Cmd = new oledbcommand(str,cn)
Dim dr as new oledbreader
Dr=cmd.executereader
While dr.read()
Combobox1.item.add(dr.item(0))
Combobox1.item.add(dr.item(1))
End while

Feature / advantages of ADO.Net


• Interoperability
• Ado.net can take advantage of flexibility and broad acceptance of XML. Through
XML we can transmit data across any network.
• Maintainability
• It divides server task in one logic processing and user interface processing on 2
separate tier on separate machine.
• Programmability
• Ado.net component provide data access functionality which is easy to read,write
and search
• Performance
• Here performance is high because datatype conversion does not take place.
CBPCC
5
• Scalability
• It has disconnected environment so at one time we can handle multiple users.

Code for Inserting Values:

Method1:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

Dim str As String


Try
str = "Insert into stud_details
values(@stud_id,@stud_name,@stud_sub1,@stud_sub2,@stud_sub3,@total,@percent
age)"
cmd = New OleDbCommand(str, cn)
cmd.Parameters.AddWithValue("@stud_id", Val(TextBox1.Text))
cmd.Parameters.AddWithValue("@stud_name", TextBox2.Text)
cmd.Parameters.AddWithValue("@stud_name", TextBox2.Text)
cmd.Parameters.AddWithValue("@stud_sub1", Val(TextBox3.Text))
cmd.Parameters.AddWithValue("@stud_sub2", Val(TextBox4.Text))
cmd.Parameters.AddWithValue("@stud_sub3", Val(TextBox5.Text))
cmd.Parameters.AddWithValue("@total", Val(TextBox6.Text))
cmd.Parameters.AddWithValue("@percentage", Val(TextBox7.Text))

If cmd.ExecuteNonQuery Then
MsgBox("record Inserted")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Method 2:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim str As String
Try
str = "insert into stud_details(stud_id,stud_name,sub1,sub2,sub3) values(" &
Val(TextBox1.Text) & ",'" & TextBox2.Text & "'," & Val(TextBox3.Text) & "," &
Val(TextBox4.Text) & "," & Val(TextBox5.Text) & ")"
cmd = New OleDbCommand(str, cn)
If cmd.ExecuteNonQuery() Then
MsgBox("Record Inserted")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
CBPCC
6
Code for Updating table:
Method1:
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim str As String
Try
str = "update stud_details set stud_name=@sname, sub1=@s1,sub2=@s2 where
stud_id=@sid "
cmd = New OleDbCommand(str, cn)
cmd.Parameters.AddWithValue("@sid", Val(TextBox1.Text))
cmd.Parameters.AddWithValue("@sname", TextBox2.Text)
cmd.Parameters.AddWithValue("@s1", Val(TextBox3.Text))
cmd.Parameters.AddWithValue("@s2", Val(TextBox4.Text))

If cmd.ExecuteNonQuery Then
MsgBox("Record Updated")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Method 2:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim str As String
Try
str = "update stud_details set stud_name='" & TextBox2.Text & "',sub1=" &
Val(TextBox3.Text) & " where stud_id=" & Val(TextBox1.Text)
str = "update stud_details set stud_name='" & TextBox2.Text & "',sub1=" &
Val(TextBox3.Text) & " where stud_id=" & Val(TextBox1.Text)
cmd = New OleDbCommand(str, cn)
If cmd.ExecuteNonQuery Then
MsgBox("Record Updated")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Code for Deleting rows from table:


Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim str As String
str = "delete from stud_details where stud_id=" & Val(TextBox1.Text)
cmd = New OleDbCommand(str, cn)
If cmd.ExecuteNonQuery Then
MsgBox("Record Deleted")
CBPCC
7
End If
End Sub
Code for searching:

Dim adap as new oledbdataadapter


Dim ds as new dataset

Adap = new oledbdataadapter (“select * from stud where rollno =”&val (textbox1.text) &
“;”,cn)

Adap.fill(ds)

If ds.tables(0).rows.count> 0 then
Textbox2.text = ds.table(0).rows(0).item(1).tostring()
Textbox3.text = ds.table(0).rows(0).item(2).tostring()
Datagridview1.datasource = ds.tables(0).defaultview

Else

Msgbox(“no record found”)


End if

Code for filling textbox by searching:

Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click


'coding for searching the record from rollno
Dim str As String

Try
Dim dr As OleDbDataReader
str = "select * from stud_details where rollno=" & Val(TextBox1.Text)
cmd = New OleDbCommand(str, cn)
dr = cmd.ExecuteReader
dr.Read()
TextBox2.Text = dr.Item(1)
TextBox3.Text = dr.Item(2)
TextBox4.Text = dr.Item(3)
TextBox5.Text = dr.Item(4)
TextBox6.Text = dr.Item(5)
TextBox7.Text = dr.Item(6)

Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

CBPCC
8
Code for Navigation( First, Next Previous Last)
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
'coding for moving to next record
If cnt < ds.Tables("st").Rows.Count - 1 Then
cnt += 1
TextBox1.Text = ds.Tables(0).Rows(cnt).Item(0)
TextBox2.Text = ds.Tables(0).Rows(cnt).Item(1)
TextBox3.Text = ds.Tables(0).Rows(cnt).Item(2)
TextBox4.Text = ds.Tables(0).Rows(cnt).Item(3)

End If

End Sub

Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click


'coding for moving to previous record
If cnt > 0 Then
cnt -= 1
TextBox1.Text = ds.Tables(0).Rows(cnt).Item(0)
TextBox2.Text = ds.Tables(0).Rows(cnt).Item(1)
TextBox3.Text = ds.Tables(0).Rows(cnt).Item(2)
TextBox4.Text = ds.Tables(0).Rows(cnt).Item(3)

End If

End Sub

Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click


'coding for moving to last record
cnt = ds.Tables("st").Rows.Count - 1

TextBox1.Text = ds.Tables(0).Rows(cnt).Item(0)
TextBox2.Text = ds.Tables(0).Rows(cnt).Item(1)
TextBox3.Text = ds.Tables(0).Rows(cnt).Item(2)
TextBox4.Text = ds.Tables(0).Rows(cnt).Item(3)

End Sub
End Class

Code to be written in form load event:


Imports System.Data.OleDb
Imports System.Data.DataSet
Imports System.Windows.Forms

CBPCC
9
Public Class marksheet
Dim cn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim adap As New OleDbDataAdapter
Dim ds As New System.Data.DataSet
Dim dr As OleDbDataReader
Dim str As String
Dim cnt As Integer = 0
Private Sub marksheet_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
'TODO: This line of code loads data into the 'Sy_studentDataSet.stud_details' table.
You can move, or remove it, as needed.
Me.Stud_detailsTableAdapter.Fill(Me.Sy_studentDataSet.stud_details)
cn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=D:\college\vb.net\sy_student.accdb")
If cn.State = Data.ConnectionState.Closed Or cn.State =
Data.ConnectionState.Broken Then
cn.Open()
End If

str = "select * from city" 'Filling combobox from database table field 'city'
cmd = New OleDbCommand(str, cn)
dr = cmd.ExecuteReader
While dr.Read
ComboBox1.Items.Add(dr.Item(1))
End While
'Below coding is for filling textbox from database
'adap = New OleDbDataAdapter("select * from stud_details", cn)
'adap.Fill(ds)
'TextBox1.Text = ds.Tables(0).Rows(0).Item(0)
'TextBox2.Text = ds.Tables(0).Rows(0).Item(1)
''Below coding is for filling datagridview from table

adap = New OleDbDataAdapter("select * from stud_details", cn)


adap.Fill(ds, "st")
DataGridView2.DataSource = ds.Tables("st").DefaultView
TextBox1.Text = ds.Tables(0).Rows(cnt).Item(0)
TextBox2.Text = ds.Tables(0).Rows(cnt).Item(1)
TextBox3.Text = ds.Tables(0).Rows(cnt).Item(2)
TextBox4.Text = ds.Tables(0).Rows(cnt).Item(3)

End Sub

CBPCC
10

You might also like