Sunteți pe pagina 1din 33

2160711

Dot Net Technology

Unit - 4
ADO.NET

Prof. Naimish R. Vadodariya


8866215253
naimish.vadodariya@darshan.ac.in
Outline
 Introduction to ADO.NET
 Architecture Of ADO.NET
 Typed DataSet
 Comparison to Classic ADO & ADO.NET
 Benefits of ADO.NET
 Data Binding: Introducing Data Source Control

Unit: 4 – ADO.NET 2 Darshan Institute of Engineering & Technology


Introduction to ADO.NET
 What is ADO.NET?
• ADO stands for ActiveX Data Objects.
• ADO.NET is a database technology of .NET Framework used to connect
application system and database server.
• ADO.NET is a part of the .NET Framework.
• ADO.NET consists of a set of classes used to handle data access.
• ADO.NET uses XML to store and transfer data among applications, which is
not only an industry standard but also provide fast access of data for
desktop and distributed applications.

Unit: 4 – ADO.NET 3 Darshan Institute of Engineering & Technology


Architecture Of ADO.NET
 The ADO.NET architecture has two main parts:
• Data(Managed) Provider (Connected Objects or Connection oriented
objects)
• DataSet (Disconnected objects or connectionless objects)

Unit: 4 – ADO.NET 4 Darshan Institute of Engineering & Technology


Architecture Of ADO.NET Cont..
Connected Objects Disconnected objects
or Connection oriented objects or Connectionless objects

Unit: 4 – ADO.NET 5 Darshan Institute of Engineering & Technology


Data Providers
Data Provider Description
SQL Server • Provides data access for Microsoft SQL server.
• Uses the System.Data.SqlClient namespace.
• Example
o SQLServer 2000, 2005, 2008 &Many more versions.
OLEDB • For data sources exposed by using OLEDB.
• Uses the System.Data.OleDb namespace.
• Example
o For both relational and non-relational databases. (Oracle, Sql-
Server, Excel, raw files, etc)
ODBC • For data sources exposed by using ODBC.
• Uses the System.Data.Odbc namespace.
• Example
o Only for relational databases (Sql Server, Oracle etc)
Oracle • For Oracle data sources.
• Uses the System.Data.OracleClient namespace.
• Example
o Oracle 8, 8i, 9i & Many more versions

Unit: 4 – ADO.NET 6 Darshan Institute of Engineering & Technology


Data Providers Cont..
 The .NET framework Data Provider is a component that has been
explicitly designed for data manipulation.
 .NET Framework data provider is used for connecting to a
database, executing commands, and retrieving results.
 The Data Provider has four core objects:
1. Connection
2. Command
3. Data Reader
4. Data Adapter

Unit: 4 – ADO.NET 7 Darshan Institute of Engineering & Technology


1) Connection
 The Connection object is the first component of ADO.NET.
 The Connection objects provider connectivity to a data source.
 It establishes a connection to a specific data source.
 Connection object helps in accessing and manipulating a
database.
 The base class for all Connection objects is the DbConnection
class.

Unit: 4 – ADO.NET 8 Darshan Institute of Engineering & Technology


Example - Connection String
SQL Server
Name
OR Instance
Name

string conString = @"Data Source=DARSHAN\SQL2005; Initial


Catalog=Master; Integrated Security=true";

it specifies that connection


Database Name will be established using
windows authentication.

string conString = @"Data Source=DARSHAN\SQL2005; Initial


Catalog=Master; user id=abc; password=123";

it specifies that connection will be established using


sql server authentication.
Unit: 4 – ADO.NET 9 Darshan Institute of Engineering & Technology
1) Connection Cont..
 Properties of Connection Object
• ConnectionString: Connection String is collection of name/value pairs
separated by semicolon which gives information of data source with which
connection needs to be established.
• Data Source: it specifies name of computer and SQL server instance with
which connection is required.
• Integrated Security: it specifies that connection will be established using
windows authentication of SQL Server username/password.
• Initial Catalog: it specifies name of database with which connection is
required.
• User ID: it specifies username to connect with database.
• Password: it specifies password to connect with database.

Unit: 4 – ADO.NET 10 Darshan Institute of Engineering & Technology


1) Connection Cont..
 Methods of Connection Object
✔ Open(): this method opens connection using information provided by
connection string.
✔ Close(): this method closes already opened connection.

Unit: 4 – ADO.NET 11 Darshan Institute of Engineering & Technology


2) Command
 The Command object enables access to database commands to
return data, modify data, run stored procedures, and send or
retrieve parameter information.
 It executes a command against a data source. Exposes Parameters
and can execute in the scope of a Transaction from a Connection.
 You can execute SQL queries to return data in a DataSet or a
DataReader object.
 Command object performs the standard Select, Insert, Delete and
Update T-SQL operations.
 The base class for all Command objects is the DbCommand class.

Unit: 4 – ADO.NET 12 Darshan Institute of Engineering & Technology


Properties of Command Object
 Connection: It specifies that on which connection command
executes.
 CommandType: It specifies type of Command to execute
• Text – SQL Statement as command type
• StoredProcedure – Stored Procedure as command type
• TableDirect – Table Name as command type
 CommandText: Either SQL Statement or name of Stored
procedure or name of Database table.

Unit: 4 – ADO.NET 13 Darshan Institute of Engineering & Technology


Methods of Command Object
 ExecuteReader(): The ExecuteReader method executes the command
specified and returns an instance of SqlDataReader class. It is used to
Select data from database.
 ExecuteNonQuery(): This method executes the command specifies
and returns the number of rows affected. It is used for insert,
update and delete operations.
 ExecuteScalar(): This method executes the command specifies and
returns the first column of first row of the result set. The remaining
rows and column are ignored.
 ExecuteXmlReader():This method executes the command specified
and returns an instance of XmlReader class. This method can be used
to return the result set in the form of an XML document.
 CreateCommand(): This method created new command object on
given connection object.

Unit: 4 – ADO.NET 14 Darshan Institute of Engineering & Technology


3) DataReader
 The Data Reader provides a high-performance stream of data from
the data source.
 It reads a forward-only, read-only stream of data from a data
source.
 DataReader object works in connected way.
 The base class for all DataReader objects is the DbDataReader
class.
 Methods of DataReader object
• Read(): this method reads next row from DataReader object, if row exists it
returns true otherwise it returns false.

Unit: 4 – ADO.NET 15 Darshan Institute of Engineering & Technology


4) DataAdapter
 The Data Adapter provides the bridge between the Data Set object
and the data source.
 The Data Adapter uses command object to execute SQL
commands at the data source to both load the Data Set with data
and reconcile changes that were made to the data in the dataset
back to the data source.
 It populates a DataSet and resolves updates with the data source.
 The base class for all DataAdapter objects is the DbDataAdapter
class.

Unit: 4 – ADO.NET 16 Darshan Institute of Engineering & Technology


Methods of DataAdapter object
 Fill(): this method takes the results of a database query from a
Command object and pushes them into a DataSet.
 Update(): this method will negotiate any changes to a DataSet
back to the original data source.

Unit: 4 – ADO.NET 17 Darshan Institute of Engineering & Technology


Example – Database Connectivity
//Step 1: Prepare Connection
SqlConnection objConnection = new SqlConnection();
objConnection.ConnectionString =
@“Data Source=ComputerName\SQLInstance;Initial Catalog=DatabaseName;
Integrated Security=False; User ID=Abc; Password=123;";
objConnection.Open();

//Step 2: Prepare & Execute Command


SqlCommand objCommand = new SqlCommand();
objCommand.Connection = objConnection;
objCommand.CommandType = CommandType.Text;
objCommand.CommandText = "SELECT CountryID, CountryName FROM Country ORDER BY
CountryName";

//Step 3: Collect Data to DataReader object which has been received as a


result of Command
SqlDataReader objSDR = objCommand.ExecuteReader();
gvCountry.DataSource = objSDR;
gvCountry.DataBind();
objConnection.Close();

Unit: 4 – ADO.NET 18 Darshan Institute of Engineering & Technology


DataSet (Disconnected objects)
 DataSet object is central to
supporting disconnected,
distributed data scenarios with
ADO.NET.
 DataSet is a memory-resident
representation of data that
provides consistent relational
programming model regardless
of the data source.
 DataSet represents a complete
set of data, including related
tables, constraints, and
relationship among the table.

Unit: 4 – ADO.NET 19 Darshan Institute of Engineering & Technology


DataSet Cont..
 Dataset has two major objects:
1) DataTable Collection:
• Data table collection contains all the data table objects in a dataset.
• A Data table is defined in the System.Data namespace and represents a
single table of memory-resident data.
• It contains a collection of columns represented by a data column collection,
and constraints represented by a constraint collection, which together
define the schema of the table.

Unit: 4 – ADO.NET 20 Darshan Institute of Engineering & Technology


DataSet Cont..
2) DataRelation Collection:
• A relationship represented by the Data relation object, associated rows in
one Data table with rows in another Data table.
• A relationship is analogous to a join path that might exist between primary
and foreign key columns in a relational database.
• A data relation identifies matching columns in two tables of a dataset.
• The essential element of a data relation are:
o Name of the relationship
o Name of the tables being related
o Related column in each table
• Relationship can be built with more than one column per table by
specifying an array of Data Column objects as the key columns.

Unit: 4 – ADO.NET 21 Darshan Institute of Engineering & Technology


Example - DataSet
//Step 1: Prepare Connection
SqlConnection objConnection = new SqlConnection();
objConnection.ConnectionString =
@"Data Source=ComputerName\SQLInstance;Initial
Catalog=DatabaseName;Integrated Security=False; User ID=Abc;
Password=123;";

//Step 2: Prepare & Execute Command


SqlCommand objCommand = new SqlCommand();
objCommand.Connection = objConnection;
objCommand.CommandType = CommandType.Text;
objCommand.CommandText = "SELECT CountryID, CountryName FROM Country
ORDER BY CountryName";

SqlDataAdapter sda = new SqlDataAdapter(objCommand);


DataSet ds = new DataSet();
sda.Fill(ds);

Unit: 4 – ADO.NET 22 Darshan Institute of Engineering & Technology


Typed Dataset
 Along with late bound access to values through weakly typed
variables, the DataSet provides access to data through a strongly
typed metaphor.
 Tables and columns that are part of the DataSet can be accessed
using user-friendly names and strongly typed variables.
 A typed DataSet is a class that derives from a DataSet.
 It inherits all the methods, events, and properties of a DataSet.
Additionally, a typed DataSet provides strongly typed methods,
events, and properties.
 This means you can access tables and columns by name, instead of
using collection-based methods.

Unit: 4 – ADO.NET 23 Darshan Institute of Engineering & Technology


Typed Dataset Cont..
 Aside from the improved readability of the code, a typed DataSet
also allows the Visual Studio .NET code editor to automatically
complete lines as you type.
 Additionally, the strongly typed DataSet provides access to values
as the correct type at compile time.
 With a strongly typed DataSet, type mismatch errors are caught
when the code is compiled rather than at run time.

Unit: 4 – ADO.NET 24 Darshan Institute of Engineering & Technology


Creating a Typed DataSet
 Open Visual Studio and Click on File  New  Project and Select
Console Application.
 Enter name for the project, Say TypedDataSetTest.
 Right click on the solution and click on Add  Add New Item
 Select XMLSchema from templates pane, give the name (Say
TypedDs.xsd) and click on Open. This will add file by name
TypedDs.xsd to the solution.
 Click on the Server Explorer browse to the database and drop the
table on the TypedDs.xsd file.

Unit: 4 – ADO.NET 25 Darshan Institute of Engineering & Technology


Classic ADO v/s ADO.NET
ADO ADO.NET
ADO is based on COM : Component Object ADO.Net is based on CLR : Common
Modelling based. Language Runtime based.
ADO.Net stores data in XML format
ADO stores data in binary format. i.e. parsing of data.
ADO can’t be integrated with XML because ADO.Net can be integrated with XML as
ADO have limited access of XML. having robust support of XML.
In ADO, data is provided by RecordSet. In ADO.Net data is provided by DataSet or
DataAdapter.
ADO is connection oriented means it ADO.Net is disconnected, does not need
requires continuous active connection. continuous connection.
ADO gives rows as single table view, it scans ADO.Net gives rows as collections so you can
sequentially the rows using MoveNext access any record and also can go through a
method. table via loop.
Using a single connection instance, ADO can Using a single connection instance, ADO.Net
not handle multiple transactions. can handle multiple transactions.

Unit: 4 – ADO.NET 26 Darshan Institute of Engineering & Technology


Benefits of ADO.NET
 ADO.NET brings with it a number of benefits, which fall into the
following categories:
• Interoperability
The ability to communicate across heterogeneous environments.
• Scalability
The ability to serve a growing number of clients without degrading system
performance.
• Productivity
The ability to quickly develop robust data access applications using
ADO.NET's rich and extensible components.
• Firewall
As In ADO.NET transmission is via XML Format, therefore it can pass
through firewalls.

Unit: 4 – ADO.NET 27 Darshan Institute of Engineering & Technology


SqlDataSource Control
 The SqlDataSource data source control represents data in an SQL
relational database to data-bound controls.
 You can use the SqlDataSource control in conjunction with a data-
bound control to retrieve data from a relational database and to
display, edit, and sort data on a web page with little or no code.
 SqlDataSource control inherited from DataSourceControl class,
which provides common functionality for all of these data source
controls.
 The SqlDataSource class provides a FilterExpression property that
can be used to filter the results of calling the SqlDataSource
class‘s Select method.

Unit: 4 – ADO.NET 28 Darshan Institute of Engineering & Technology


SqlDataSource Control Cont..
 The SqlDataSource can support any SQL relational database that
can be connected using an ADO.NET provider, such as the
SqlClient, OleDb, Odbc, or OracleClient.
 Let’s See how to Select, Insert, Update data from database using
SqlDataSource control without writing a single line of code.
 Select Data From a Database

<asp:SqlDataSource ID="sdsCustomer" runat="server"


ConnectionString="<%$ConnectionStrings:CustomerConnectionString
%>"
SelectCommand="SELECT [CustomerId], [CNAME], [CITY] FROM
[CUSTOMERS]">
</asp:SqlDataSource>

Unit: 4 – ADO.NET 29 Darshan Institute of Engineering & Technology


Inserting data into database
<asp:SqlDataSource ID="sdsCustomer" runat="server"
ConnectionString="<%$ ConnectionStrings:CustomerConnectionString
%>"

InsertCommand="Insert Into [CUSTOMERS] (CustomerId,CNAME,CITY)


VALUES (@CustomerId,@CNAME,@CITY)">

<InsertParameters>
<asp:FormParameter Name="CustomerId"
FormField=“txtCustomerId" />
<asp:FormParameter Name="CNAME" FormField=“txtCNAME" />
<asp:FormParameter Name="CITY" FormField=“txtCITY" />
</InsertParameters>

</asp:SqlDataSource>

Unit: 4 – ADO.NET 30 Darshan Institute of Engineering & Technology


Updating data into database
<asp:SqlDataSource ID="sdsCustomer" runat="server"
ConnectionString="<%$ ConnectionStrings:CustomerConnectionString
%>“

UpdateCommand="UPDATE [CUSTOMERS] SET CNAME = @CNAME, CITY =


@CITY WHERE CustomerId = @CustomerId">

<UpdateParameters>
<asp:FormParameter Name="CustomerId"
FormField=“txtCustomerId" />
<asp:FormParameter Name="CNAME" FormField=“txtCNAME" />
<asp:FormParameter Name="CITY" FormField=“txtCITY" />
</UpdateParameters>

</asp:SqlDataSource>

Unit: 4 – ADO.NET 31 Darshan Institute of Engineering & Technology


Delete data from database
<asp:SqlDataSource ID="sdsCustomer" runat="server"
ConnectionString="<%$ ConnectionStrings:CustomerConnectionString
%>“

DeleteCommand="Delete FROM [CUSTOMERS] Where CustomerId =


@CustomerId“ DeleteCommandType="Text">

<DeleteParameters>
<asp:Parameter Name="CustomerId” Type="Int32" />
</DeleteParameters>

</asp:SqlDataSource>

Unit: 4 – ADO.NET 32 Darshan Institute of Engineering & Technology


Thank you

S-ar putea să vă placă și