1. ADO.NET FUNDAMENTALS
Desktop and web applications are data-driven.
These applications are largely concerned with retrieving,
displaying, and modifying data.
The .NET Framework includes its own data access technology:
ADO.NET.
ADO.NET consists of managed classes that allow .NET applications
to connect to data sources, execute commands, and manage
disconnected data.
In ASP.NET, there are a few ways to get information out of a
database without directly using the ADO.NET classes.
The SqlDataSource control
LINQ to SQL
1 Profiles:
2. The ADO.NET Architecture
ADO.NET uses a multilayered architecture that revolves around a
few key concepts, such as Connection, Command, and DataSet
objects.
Differences between ADO.NET and some other database
technologies is how it deals with the challenge of different data
sources
In classic ADO, programmers use a generic set of objects no matter
what the underlying data source is.
ADO.NET, which uses a data provider model.
2
3. ADO.NET Data Providers
A data provider is a set of ADO.NET classes that allows you to access a specific
database, execute SQL commands, and retrieve data.
Essentially, a data provider is a bridge between your application and a data
source.
The classes that make up a data provider include the following:
Connection : Used to establish a connection to a data source.
Command : Used to execute SQL commands and stored
procedures.
DataReader : This object provides fast read-only, forward-only
access to the data retrieved from a query.
DataAdapter : Use it to fill a DataSet (a disconnected collection of
tables and relationships) with information extracted
from a data source and apply changes to a data
source.
3
4. ADO.NET Data Providers cont..
ADO.NET doesn’t include generic data provider objects.
Instead, it includes different data providers specifically designed
for different types of data sources.
Each data provider has a specific implementation of the
Connection, Command, DataReader, and DataAdapter classes that’s
optimized for a specific RDBMS.
For example, to create a connection to a SQL Server database, use
a connection class named SqlConnection.
ADO.NET provider model is that it’s extensible, developers can
create their own providers for proprietary data sources
4
5. ADO.NET Data Providers cont..
The .NET Framework is bundled with a small set of four providers:
SQL Server provider: Provides optimized access to a SQL Server
database (version 7.0 or later).
OLE DB provider: Provides access to any data source that has an
OLE DB driver. This includes SQL Server databases prior to version
7.0.
Oracle provider: Provides optimized access to an Oracle database
(version 8i or later).
ODBC provider: Provides access to any data source that has an
ODBC driver.
5
7. SQL Server 2005
ADO.NET provides support for a few features that are
limited to SQL Server 2005
MARS (multiple active result sets)
User-defined data types
Managed stored procedures
SQL notifications
Snapshot transaction isolation
7
8. Fundamental ADO.NET Classes
ADO.NET has two types of objects: connection-based and content-based.
Connection-based objects :
Data provider objects such as Connection, Command, DataReader, and
DataAdapter.
Allows to connect to a database, execute SQL statements, move through
a read-only result set, and fill a DataSet.
Specific to the type of data source, and found in a provider-specific
namespace
Content-based objects:
Objects are really just “packages” for data
Include DataSet, DataColumn, DataRow, DataRelation, and several
others.
8
9. Fundamental ADO.NET Classes cont..
The ADO.NET Namespaces
Namespace Description
System.Data Contains the key data container classes that model columns,
relations,tables, datasets, rows, views, and constraints
System.Data.Common Contains base, mostly abstract classes that implement some of
the interfaces from System.Data and define the core ADO.NET
functionality
System.Data.OleDb Contains the classes used to connect to an OLE DB provider
System.Data.SqlClient Contains the classes you use to connect to a Microsoft SQL
Server database
System.Data. Contains the classes required to connect to an Oracle database
OracleClient
System.Data.Odbc Contains the classes required to connect to most ODBC drivers
System.Data.SqlTypes Contains structures that match the native data types in SQL
9 Server.
10. The Connection Class
The Connection class allows you to establish a connection to the
data source.
Before accessing database need to establish database connection.
The core Connection properties and methods are specified by the
IDbConnection interface, which all Connection classes implement.
Connection Strings : When you create a Connection object, you
need to supply a connection string.
The server where the database is located
The database you want to use
How the database should authenticate you.
10
11. The Connection Class cont..
For example
string connectionString = "Data Source=localhost; Initial Catalog=Northwind;"
+ "Integrated Security=SSPI“;
For a newly installed SQL Server database, the sa (system administrator) account
is usually present
string connectionString = "Data Source=localhost; Initial Catalog=Northwind;"
+ "user id=sa; password=opensesame";
If you’re using the OLE DB provider, string must provider setting
string connectionString = "Data Source=localhost; Initial Catalog=Sales;" +
"user id=sa; " +
password=da#ta_li#nk_43;Provider=MSDAORA";
For access database:-
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data Source=C:DataSourcesNorthwind.mdb";
11
12. The Connection Class cont..
Don’t hard-code a connection string.
<connectionStrings> section of the web.config file is a handy place to store your
connection. Here’s an example
<configuration>
<connectionStrings>
<add name="Northwind" connectionString=
"Data Source=localhost; Initial Catalog=Northwind;
Integrated Security=SSPI"/>
</connectionStrings>
...
</configuration>
Retrieve your connection string by name from the
WebConfigurationManager.ConnectionStrings collection
string connectionString =
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
Note : Import the System.Web.Configuration namespace.
12
13. Testing a Connection
To use this code as written, you must import the System.Data.SqlClient namespace
// Create the Connection object.
string connectionString =
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
try
{
con.Open();
lblInfo.Text = "<b>Server Version:</b> " + con.ServerVersion;
lblInfo.Text += "<br /><b>Connection Is:</b> " + con.State.ToString();
}
catch (Exception err)
{
lblInfo.Text = "Error reading the database. " + err.Message;
}
finally
{
con.Close();
lblInfo.Text += "<br /><b>Now Connection Is:</b> " +
13
con.State.ToString();
}
14. Connection Pooling
Connections are a limited server resource. (open the connection as
late as possible and release it as quickly as possible.)
Acquiring a connection takes a short, but definite, amount of time,
becomes a overhead, affects scalability of web application
One solution is connection pooling. Connection pooling is the practice
of keeping a permanent set of open database connections
Connection pools in ADO.NET are completely transparent to the
programmer.
ADO.NET does not include a connection pooling mechanism. However,
most ADO.NET providers implement some form of connection pooling.
The SQL Server and Oracle data providers implement their own
efficient connection pooling algorithms.
14
15. Connection Pooling cont…
Setting Description
Max Pool Size Max. no. of pools allowed in the pool(default to 100).If
max no. reached, any further attempts to open conn are
queued until conn becomes available
Min Pool Size The minimum number of connections always retained the
pool(default to 0).
Pooling When true, conn is drawn from appropriate pool, or if
necessary ,is created and added to appropriate pool.
Connection Lifetime Specifies time interval in seconds.
We can put these settings in connection string in key/value pair.
15
16. The Command and DataReader Classes
The Command class allows you to execute any type of
SQL statement.
can use a Command class to perform data definition
tasks, but much more likely to perform data manipulation
tasks.
The provider-specific Command classes implement
standard functionality, like connection classes.
The IDbCommand interface defines a few key properties
and the core set of methods that are used to execute a
command over an open connection.
16
17. Command Basics
Before you can use a command,
Choose the command type
Set the command text
Bind the command to a connection
Pass the information needed depending upon command type
Values for the CommandType Enumeration
Value Description
CommandType.Text The command will execute a direct SQL statement.
CommandText property provides SQL statement
CommandType. The command will execute a stored procedure in the
StoredProcedure data source.
The CommandText property provides the name of the
stored procedure.
CommandType. The command will query all the records in the table.
TableDirect The CommandText is the name of the table from which
17
the command will retrieve the records.
18. Command Basics cont..
For example, here’s how you would create a Command object that represents a
query.
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Employees";
More efficient way, use one of the Command constructors
SqlCommand cmd = new SqlCommand(“select * FROM Employees“,
con);
Alternatively, to use a stored procedure,
SqlCommand cmd = new SqlCommand("GetEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
18
19. Command object…
The Command object provides three methods that you can use to
perform the command.
Command Methods:
Method Description
ExecuteNonQuery() Executes non-SELECT commands, such as SQL
commands that insert, delete, or update
records.
ExecuteScalar() Executes a SELECT query and returns the
value of the first field of the first row from the
rowset generated by the command.
ExecuteReader() Executes a SELECT query and returns a
DataReader object that wraps a read-only,
forward-only cursor.
19
20. The DataReader Class
A DataReader allows you to read the data returned by a SELECT
command one record at a time, in a forward-only, read-only stream.
Sometimes called a firehose cursor.
Using a DataReader is the simplest way to get to your data, but it lacks
the sorting and relational abilities of the disconnected DataSet
Core methods of the DataReader
Read()
GetValue()
GetValues()
GetInt32(),GetChar(),GetDateTime(), GetXxx()
NextResult()
Close()
20
21. The DataReader Class cont..
The following example creates a simple query command to return all the
records from the Employees table.
protected void Page_Load(object sender, EventArgs e)
{
// Create the Command and the Connection objects.
string connectionString =
WebConfigurationManager.ConnectionStrings["Northwind"].
ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
string sql = "SELECT * FROM Employees";
SqlCommand cmd = new SqlCommand(sql, con);
...
// Open the Connection and get the DataReader.
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
21 ...
22. The DataReader Class cont..
The ExecuteReader() method has an overloaded version that takes
one of the values from the CommandBehavior enumeration as a
parameter.
One useful value is CommandBehavior.CloseConnection.
When you pass this value to the ExecuteReader() method, the
DataReader will close the associated connection as soon as you close
the DataReader.
SqlDataReader reader =
cmd.ExecuteReader(CommandBehavior.CloseConnection);
// (Build the HTML string here.)
// No need to close the connection. You can simply close the reader.
reader.Close();
…..
22
23. Processing Multiple Result Sets
The command you execute can return a multiple result sets.
A command can return more than one result set in two ways:
If you’re calling a stored procedure, it may use multiple SELECT
statements
If you’re using a straight text command, you may be able to batch
multiple commands by separating commands with a semicolon (;)
Here’s an example
string sql = "SELECT TOP 5 * FROM Employees;" +
"SELECT TOP 5 * FROM Customers; SELECT TOP 5 *
FROM Suppliers“
Initially DataReader provides access from the Employees table.
Once you’ve finished using the Read() method to read all these records, you can
call NextResult() to move to the next result set.
23
24. The ExecuteScalar() Method
The ExecuteScalar() method returns the value stored in the first field of
the first row of a result set generated by the command’s SELECT query.
Usually used to execute a query that retrieves only a single field, perhaps
calculated by a SQL aggregate function such as COUNT() or SUM().
For Example
SqlConnection con = new SqlConnection(connectionString);
string sql = " SELECT COUNT(*) FROM Employees ";
SqlCommand cmd = new SqlCommand(sql, con);
// Open the Connection and get the COUNT(*) value.
con.Open();
int numEmployees = (int)cmd.ExecuteScalar();
con.Close();
// Display the information.
HtmlContent.Text += "<br />Total employees: <b>" +
numEmployees.ToString() + "</b><br />";
24
25. The ExecuteNonQuery() Method
The ExecuteNonQuery() method executes commands that don’t return a result
set, such as INSERT, DELETE, and UPDATE.
The ExecuteNonQuery() method returns a single piece of information—the
number of affected records
Here’s an example:
SqlConnection con = new SqlConnection(connectionString);
string sql = "DELETE FROM Employees WHERE EmployeeID = “ + empID.ToString();
SqlCommand cmd = new SqlCommand(sql, con);
try
{
con.Open();
int numAff = cmd.ExecuteNonQuery();
HtmlContent.Text = “Number of Records affected” + numAff.toString();
}
catch (SqlException exc)
{
}
finally
{
25
con.Close();
}
26. Using Parameterized Commands
A parameterized command is simply a command that uses
placeholders in the SQL text.
The placeholders indicate dynamically supplied values, which are
then sent through the Parameters collection of the Command object.
For example,
SELECT * FROM Customers WHERE CustomerID = 'ALFKI'
It would become something like this:
SELECT * FROM Customers WHERE CustomerID = @CustID3
The placeholders are then added separately and automatically
encoded.
26
27. Calling Stored Procedures
A stored procedure is a batch of one or more SQL statements
that are stored in the database.
Stored procedures are similar to functions in that they are
well-encapsulated blocks of logic that can accept data (through
input parameters) and return data.
Stored procedures have many benefits:
They are easier to maintain.
They allow you to implement more secure database usage
They can improve performance
27
28. Calling Stored Procedures cont..
Here’s the SQL code needed to create a stored procedure for inserting a single record into
the Employees table
IF EXISTS (SELECT name FROM sysobjects
WHERE name = InsertEmployee' AND type = 'P')
DROP PROCEDURE InsertEmployee
GO
CREATE PROCEDURE InsertEmployee
@TitleOfCourtesy varchar(25),
@LastName varchar(20),
@FirstName varchar(10),
@EmployeeID int OUTPUT
AS
INSERT INTO Employees
(TitleOfCourtesy, LastName, FirstName, HireDate)
VALUES (@TitleOfCourtesy, @LastName, @FirstName,
GETDATE());
SET @EmployeeID = @@IDENTITY
28
29. Calling Stored Procedures cont..
Next, you can create a SqlCommand to wrap the call to the stored procedure.
string connectionString =
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
// Create the command for the InsertEmployee stored procedure.
SqlCommand cmd = new SqlCommand("InsertEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
Now add the stored procedure’s parameters to the Command.Parameters collection.
cmd.Parameters.Add(new SqlParameter("@TitleOfCourtesy", SqlDbType.NVarChar, 25));
cmd.Parameters["@TitleOfCourtesy"].Value = title;
cmd.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 20));
cmd.Parameters["@LastName"].Value = lastName;
cmd.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 10));
cmd.Parameters["@FirstName"].Value = firstName;
The last parameter is an output parameter.
cmd.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 4));
cmd.Parameters["@EmployeeID"].Direction = ParameterDirection.Output;
29
30. Calling Stored Procedures cont..
ADDING PARAMETERS WITH IMPLICIT DATA TYPES:
One handy shortcut is the AddWithValue() method of
the Parameters collection.
This method takes the parameter name and the value
but no data type information.
It infers the data type from the supplied data.
Here’s an example:
cmd.Parameters.AddWithValue("@LastName", lastName);
cmd.Parameters.AddWithValue("@FirstName" firstName);
30