Post on 06-Apr-2018
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 1/15
Exploring VB.NET Data Access with ADO.NET
Data Access with ADO.NET
At the end of this chapter you will be able to understand the basic architecture of
ADO.NET and its objects. This chapter discusses the DataView object along with other techniques use to filter the data.
SCOPE
7.1 Introduction to ADO.NET7.1.1 Connection Object
7.1.2 Command Object
7.1.3 DataReader Object7.1.4 DataAdapter Object
7.1.5 DataSet Object
7.1.5.1 Data Filtering7.1.5.1.1 Select Method
7.1.5.1.2 DataView
© Copyright 2006, Tata Consultancy Services Limited (TCS). 150
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 2/15
Exploring VB.NET Data Access with ADO.NET
7.1 Introduction to ADO.NET
ADO.NET is designed with the goal of better serving the data access needs of web
applications. ADO.NET is designed to be data-centric, non-database-centric, focused onhandling disconnected data sets, and tightly integrated with XML. It enables better data
sharing capabilities between components and tiers in an application.
The .NET Data Provider object group contains objects for accessing SQL Server and
OLEDB data sources and includes Connection and Command objects that are similar to
their ADO counterparts. A .NET data provider is used for connecting to a database,
executing commands, and retrieving results. Those results are either processed directly,or placed in an ADO.NET DataSet in order to be exposed to the user. The objects are:
Connection Object
Command Object
DataReader Object
DataAdapter Object
DataSet Object
7.1.1 Connection Object
The .NET Data Provider Connection object is used to set a connection to a data source.
It is similar to ADO Connection object. Each .NET Provider has its own Connection
object. The SQL Server .NET Provider includes a SqlConnection Object, while the OLE
DB .NET Provider includes an OleDbConnection object. These are simply different
flavours of the same kind of object. If you decide to create your own .NET Provider then
it must provide the standard set of .NET Provider Object.
The ADO.NET Connection object accepts one string parameter called connectionString
for assigning the data source connection details.
Ideally the string for connectionString should be written as follows:
Provider=SQLOLEDB.1; Data Source=MySQLServer; InitialCatalog=NORTHWIND; uid=sa; pwd=;
For the SqlConnection object this string is like a typical OLE DB Provider string,
except that you omit the Provider parameter.
© Copyright 2006, Tata Consultancy Services Limited (TCS). 151
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 3/15
Exploring VB.NET Data Access with ADO.NET
Imports System.Data.SqlClient
Dim SqlConn As SqlConnection = New SqlConnection ("Data Source=tilesd; Initial Catalog=Northwind; uid=SA; pwd= ;")
7.1.2 Command Object
The Command object allows executing a SQL statement or stored procedure in a data
source. On executing the Command object, either a row set containing data is returnedthat is passed to another object such as DataReader/ DataAdapter or it returns a count of
number of records affected for queries that do not return a row set.
There are two command objects, one for OLEDB and other one for SQL as given below:
SqlCommand : Uses Tabular Data Services with MS SQL Server
OleDbCommand : Used with OLE-DB provider or OLE-DB/ODBC driver
The syntax of creating an instance of Command object and how to execute it is given
below:
Dim myCommand As New SqlCommand (<SQL Statement>, <Connection name>)myCommand.Connection.Open ()myCommand.ExecuteNonQuery ()
Where myCommand is a Command type object containing two parameters, first one is
SQL statement to be executed such as INSERT, UPDATE or DELETE and second is
name of the Connection object.
The Command object is used to execute stored procedures and Transact-SQL statementsagainst a data source. It is having similar functions to that of ADO Command Object. The
SqlCommand object works with SqlConnection object to execute statements. It is very
versatile and will execute a number of different kinds of statements using the methods.
The two commands are virtually identical, with the only real difference being that theSqlCommand class exposes an execute method (ExecuteXmlReader ()) for returning an
XML stream that the OleDbCommand class does not. This is a capability given to the
SqlCommand class based on the XML capabilities of SQL Server 7.0 and greater.
To create and initialize an instance of SqlCommand object the SqlCommand’s New ()
constructor is used. This SqlCommand constructor is said to be overloaded. (Overloaded
means it provides several versions of the same New () method.) .
© Copyright 2006, Tata Consultancy Services Limited (TCS). 152
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 4/15
Exploring VB.NET Data Access with ADO.NET
7.1.3 DataReader Object
The DataReader object is squarely aimed at web developers. It provides a data, read-
only, forward-only data stream that is designed to provide quick access to data.
The DataReader object will retrieve multiple resultset, such as data from two separatetables in the database. It will also return schema information for the underlying datasource.
Each .NET Data Provider includes its own version of the DataReader object. The SQL
Server Managed Provider includes the SqlDataReader object where as OLE DB
Managed Provider includes the OleDbDataReader object.
SqlDataReader or OleDbDataReader object is created with the help of ExecuteReader method. While the SqlDataReader or OleDbDataReader is in use, the Connection object
is serving the DataReader. In this state, no other operations can be performed on the
Connection object other than closing it. This will be the case until the Close method is
called.
Let’s see the syntax of making an instance of SqlDataReader and OleDbDataReader object:
SqlCommand sqlCmd =New SqlCommand (<SQL Statement>, <Connection name>)Connection.Open ()Dim sqlReader As SqlDataReaderSqlReader = sqlCmd.ExecuteReader ()
ExecuteReader method provides two overloaded methods. The first takes no parameter
and the second takes an enumerated value of CommandBehavior type that is defined inSystem.Data. The CommandBehavior specifies a description of the results and the affect
on the database of the query command.
7.1.4 DataAdapter Object
The DataAdapter object is a very important member of the Managed Data Provider
because it provides the link for exchanging the data between a data source and a data set.ADO.NET Provides the DataSet object for caching and manipulating data. Data adapters
can move any kind of data between a data source and a DataSet object as long as it is
supported by a .NET Data Provider.
The DataAdapter object is used to retrieve data from a data source and populate the
DataTable objects in a DataSet. It acts like a connecting pipe between the data source
and the DataSet. The DataAdapter class provides the building blocks for disconnected
data access mechanism from a data source.
7.1.5 DataSet Object
© Copyright 2006, Tata Consultancy Services Limited (TCS). 153
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 5/15
Exploring VB.NET Data Access with ADO.NET
The .NET data access object model is based around one fundamental object – the
DataSet. It provides many features that make complex data access techniques much moreefficient, while remaining as easy to use as the Recordset object of traditional ADO. The
main advantage of DataSet is that a DataSet object can hold more than one table from the
same source, as well as the relationship between them.
We can create a DataSet from existing data in a data store. It allows us to manipulate thedata held in the DataSet’s tables, and build and/or modify the relationship between thetables within it.
DataSet object can hold more than one table and also the relationship between them.
Each table in a DataSet is a DataTable object within the DataTableCollection. EachDataTable object contains a collection of DataRow objects (within the
DataRowCollection) and a collection of DataColumn objects (within the
DataColumnCollection). There are also collections for the primary keys, constraints, anddefault values used in this table, and the parent and child relationships between the tables
which are contained in ConstraintCollection. Let’s discuss each object of DataSet.
The DataRelationCollection object represents the collection of DataRelation object for
the DataSet. A DataRelation is used to relate two DataTable objects to each other through
DataColumn objects. For example, in a Customer/Orders relationship, the Customers
table is the parent and the Orders table is the child of the relationship. This is similar to a primary key/foreign key relationship.
The DataSet’s constructor comes in three different versions. This first constructor doesn’taccept input parameters and just initialises the new instance of the DataSet object and
creates a default name “NewDataSet”. The second constructor version initialises a new
instance of DataSet class with the given name passes as the only parameter. The third
constructor initialises a new instance of the DataSet class with the SerializationInfo andthe StreamingContext where “info” refers to the data needed to serialize or deserialize an
object and context “refers” to the source and destination of a given serialized stream.DataSet object has series of methods, and properties that can be use with tables.
7.1.5.1 Data Filtering
After a dataset has been populated, our application might need to view its data in various
ways. For example, viewing the records in a specific order or seeing only a subset of the
records (that is, filter them). Because the dataset is disconnected from the data source, itis often impractical and resource-intensive to re-execute SQL commands to perform these
actions.
Instead, we can use built-in dataset features to filter and sort. We have two options:
Data tables support a Select method which we can call to filter and sort data. The
method does not change the contents or order of records in a table; instead, it presents a list of records (an array) representing the criteria specified.
Another option is to use a data view (DataView object). A data view is an object
that acts as a layer on top of the data table, providing a filtered and sorted view of
© Copyright 2006, Tata Consultancy Services Limited (TCS). 154
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 6/15
Exploring VB.NET Data Access with ADO.NET
the table's contents. (We can also use a data view manager, which acts like a
collection of data views.)
Both methods provide the same filtering and sorting capabilities. The primary difference
is that a data table's Select method can only be called in code at run time. Using a dataview, on the other hand, provides these advantages:
It gives the flexibility of creating and configuring the data view at design time,with the option to set its properties at run time as well.
It can be used in data binding; that is, binding controls to it in a designer.
It can be used to create multiple data views to see the data in a table in different
ways. For example, one data view might display data in an Orders table in dateorder, and another data view might show it in customer order.
7.1.5.1.1 Select Method
The select method is very easy and simple to use. It returns an array of DataRow objects
that match the criteria specified in the query. In addition to supplying traditional filter
expression (such as ‘Column = 5 or ‘Date<’07/07/2002’), we can also supply aDataRowViewState, allowing us to select all rows that not only match given criteria, but
have a specific version (such as added, Original, deleted, etc.).
Following table shows the overloaded list of Select method:
Overloaded Method Description
Select () This method returns the rows in order of primary key
Select (String) This method accepts a parameter to specify the criteria
to used to filter the rows
Select (String1, String2) These methods accept two parameters. First one
accepts a string specifying the criteria to used to filter the rows and second one specifying the column andsort direction
Select (String1, String2,DataViewRowState)
This method is similar to the above method but itaccepts one more parameter which accepts one of the
DataViewRowState value1.
Table 7.1
The following listing uses the select method to filter the data. This code is executed whenthe form is loaded.
conString = "Data Source=Localost\NETSDK;InitialCatalog=Northwind;uid=sa;pwd=;"
cmdString = "Select * from Employees"sqlCon = New SqlConnection(conString)ListBox1.Visible = False
Try
1 The DataRowViewState is used either to retrieve a particular version of Data from a DataRow, or to
determine which version exists
© Copyright 2006, Tata Consultancy Services Limited (TCS). 155
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 7/15
Exploring VB.NET Data Access with ADO.NET
sqlCon.Open() Catch err As Exception
MsgBox(err.ToString) End Try
ds = New DataSet()da = New SqlDataAdapter(cmdString, sqlCon)da.Fill(ds)
t = ds.Tables(0) Dim a = ds.Tables(0).Columns.Count For Each dt In ds.Tables For Each dc In dt.Columns For Each d In dt.Rows
ComboBox1.Items.Add(d(11)) Next Next Next
Listing 7.1
The code given above opens the connection to the NTSDK database found in the local
machine, and executes a SQL query. The result of this query is then added to theComboBox. The code given below is called when any item in the ComBox is selected.
Dim count = ComboBox1.SelectedItemfilterStr = "Country = '" & count & "'"dr = t.Select(filterStr)
For i = 0 To (dr.Length - 1)ListBox1.Items.Add(dr(i)("FirstName").ToString)
NextListBox1.Visible = True
Listing 7.2
Here a Select statement is used to filter the data from the DataSet. The expression given
here for Select statement is simple, but it can be far more complex depending upon theneed of the application. This line of code simply filter the data placed in DataSet by the
filter string and displayed the result in the ListBox. The output generated will look like
the figure given below:
© Copyright 2006, Tata Consultancy Services Limited (TCS). 156
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 8/15
Exploring VB.NET Data Access with ADO.NET
After selecting the country name the output will be:
Figure 7.1
7.1.5.1.2 DataView
A DataView give the option to create different views of the data stored in a DataTable.
With the help of DataView we can customize this view so that our application can control
what DataViewRowState the view is allowed to see. As well, we can supply the filter expression so that we can control which rows are accessible to see. DataView helps in
exposing the data in a table with different sort orders, and filter the data by row state or
based on a filter expression.
© Copyright 2006, Tata Consultancy Services Limited (TCS). 157
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 9/15
Exploring VB.NET Data Access with ADO.NET
A DataView provides a dynamic view of data whose content, ordering, and membership
reflect changes to the underlying DataTable as they occur. This is different from theSelect method of the DataTable, which returns a DataRow array from a table per a
particular filter and/or sort order and whose content reflects changes to the underlying
table, but whose membership and ordering remain static. The dynamic capabilities of theDataView make it ideal for data-binding applications.
DataViewManager is used to manage view settings for all the tables in a DataSet. TheDataViewManager provides a convenient way to manage default view settings for each
table. When binding a control to more than one table of a DataSet, binding to a
DataViewManager is the ideal choice.
There are two ways to create a DataView. We can use the DataView constructor, or can
create a reference to the DefaultView property of the DataTable. The DataView
constructor can be empty, or will also take either a DataTable as a single argument, or aDataTable along with filter criteria, sort criteria, and a row state filter.
The following code example demonstrates how to create a DataView using the DataViewconstructor. A RowFilter, Sort column, and DataViewRowState are supplied along with
the DataTable.
Dim DV As DataView = New DataView(ds.Tables("Customers"), _"Country = 'USA'", "ContactName", DataViewRowState.CurrentRows)
The code given below creates a DataView by creating a reference to the DefaultView
property of the DataTable
Dim DV As DataView = ds.Tables("Customers").DefaultView
The code given below uses the DataView to filter the data stored in a DataSet. Add thefollowing code in the Form_Load event:
conString = "Data Source=LN005\NETSDK;InitialCatalog=Northwind;uid=sa;pwd=;"cmdString = "Select * from Employees"sqlCon = New SqlConnection(conString)ListBox1.Visible = FalseLabel1.Visible = FalseLabel2.Visible = FalseComboBox1.Visible = FalseComboBox2.Visible = FalseButton1.Visible = FalseDataGrid1.Visible = False
TrysqlCon.Open()
Catch err As ExceptionMsgBox(err.ToString)
End Tryds = New DataSet()
© Copyright 2006, Tata Consultancy Services Limited (TCS). 158
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 10/15
Exploring VB.NET Data Access with ADO.NET
Listing 7.3
This code makes a connection to the database and executes the SQL query on this
connection. Add the following line of code in the RadioButton1_CheckedChanged event
Label1.Visible = TrueLabel2.Visible = TrueComboBox1.Visible = TrueComboBox2.Visible = TrueButton1.Visible = TrueDataGrid1.Visible = Falseda = New SqlDataAdapter(cmdString, sqlCon)da.Fill(ds)t = ds.Tables(0)
Dim a = ds.Tables(0).Columns.Count For Each dt In ds.Tables For Each dc In dt.Columns For Each d In dt.Rows
ComboBox1.Items.Add(d(5))ComboBox2.Items.Add(d(6))
Next Next Next
Listing 7.4
This code given above simply bind the data found in a particular column of the
DataTable to the ComboBox. Add the following code in the Button1_Click event
ListBox1.ResetText() Dim count1 As DateTime = ComboBox1.SelectedItem Dim count2 As DateTime = ComboBox2.SelectedItem
Dim dv As New DataView(ds.Tables(0))dv.RowFilter = "(BirthDate < '" & count1 & "') And (HireDate <'" & count2 & "')"
For i = 0 To (dv.Count - 1) Try
ListBox1.Items.Add(dv(i)("FirstName").ToString) Catch err As Exception
MsgBox("Entry Not Found !!!!") End Try Next
ListBox1.Visible = True
Listing 7.5
This line of code makes an object of DataView which accepts a DataSet’s Table as a parameter. Then it filters the row with the filter expression. This expression is set
dynamically. Using the DataView’s filter expression the result is then displayed on the
ListBox. Add the following code to view the table when the checkbox labelled “View
The Employee table” is checked
ListBox1.Visible = FalseLabel1.Visible = False
© Copyright 2006, Tata Consultancy Services Limited (TCS). 159
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 11/15
Exploring VB.NET Data Access with ADO.NET
Label2.Visible = FalseComboBox1.Visible = FalseComboBox2.Visible = FalseButton1.Visible = FalseDataGrid1.Visible = TrueDataGrid1.SetDataBinding(ds, "")
Listing 7.6
The output will be look like this:
Fig 7.2
When first RadioButton is checked, it will ask for the criteria to be used to filter the dataas given below:
© Copyright 2006, Tata Consultancy Services Limited (TCS). 160
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 12/15
Exploring VB.NET Data Access with ADO.NET
Fig 7.3
Select the BirthDate and HireDate and then press Search button, it will display thefiltered data in the ListBox as shown below:
Fig 7.4
© Copyright 2006, Tata Consultancy Services Limited (TCS). 161
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 13/15
Exploring VB.NET Data Access with ADO.NET
Now select the second check box. It will display the entire data of the Employee table as
shown below:
Fig 7.5
© Copyright 2006, Tata Consultancy Services Limited (TCS). 162
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 14/15
Exploring VB.NET Data Access with ADO.NET
SUMMARY
Key points covered in this chapter are:
.NET Data Provider Connection object is used to set a connection to a data
source.
The Command object allows executing a SQL statement or stored procedure in a
data source.
DataReader object provides a data, read-only, forward-only data stream that is
designed to provide quick access to data.
DataSet object provides the link for exchanging the data between a data sourceand a data set.
The .NET data access object model is based around one fundamental object – the
DataSet. It provides many features that make complex data access techniquesmuch more efficient
Select method returns an array of DataRow objects that match the criteria
specified in the query. A DataView give the option to create different views of the data stored in a
DataTable.
© Copyright 2006, Tata Consultancy Services Limited (TCS). 163
8/3/2019 Chapter07 - ADO.net Overview
http://slidepdf.com/reader/full/chapter07-adonet-overview 15/15
Exploring VB.NET Data Access with ADO.NET
SELF ASSESSMENT
I. State True or False:
i) The DataAdapter object provides a data, read-only, forward-only data stream(T/F)
ii) The DataReader object is used to retrieve data from a data source and populate the
DataTable objects in a DataSet. (T/F)iii) ExecuteReader method of Command object is used to make an instance of
DataReader object. (T/F)
iv) Select method returns an array of DataRow objects that match the criteriaspecified in the query. (T/F)
v) The Command object does not allow executing a stored procedure in a data
source. (T/F)
II. Fill in the blanks:
i) The DataRelationCollection object represents the collection of DataRelationobject for the ___________
ii) ______________ method gives the flexibility of creating and configuring the data
view at design time, with the option to set its properties at run time as well.iii) Data tables support a _____________ method which we can call to filter and sort
data.
iv) A ____________ give the option to create different views of the data stored in a
_____.v) _____________ is used to manage view settings for all the tables in a DataSet.
Lab Exercise
Convert the earlier database program done in VB.NET Level 1 course into SQL Server
2005 database version.
Also add other features like deleting and updating data.
© Copyright 2006, Tata Consultancy Services Limited (TCS). 164