Ch06 ado.net fundamentals

30
ADO.NET FUNDAMENTALS 1 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

description

 

Transcript of Ch06 ado.net fundamentals

Page 1: Ch06 ado.net fundamentals

ADO.NET FUNDAMENTALS

1

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 Profiles:

Page 2: Ch06 ado.net fundamentals

The ADO.NET Architecture

2

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.

Page 3: Ch06 ado.net fundamentals

ADO.NET Data Providers

3

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.

Page 4: Ch06 ado.net fundamentals

ADO.NET Data Providers cont..

4

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

Page 5: Ch06 ado.net fundamentals

ADO.NET Data Providers cont..

5

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.

Page 6: Ch06 ado.net fundamentals

ADO.NET Data Providers cont..

6 6

Figure shows the layers of the ADO.NET provider model

Page 7: Ch06 ado.net fundamentals

SQL Server 2005

7

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

Page 8: Ch06 ado.net fundamentals

Fundamental ADO.NET Classes

8

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.

Page 9: Ch06 ado.net fundamentals

Fundamental ADO.NET Classes cont..

9

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 ofthe interfaces from System.Data and define the core ADO.NETfunctionality

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 SQLServer database

System.Data.OracleClient

Contains the classes required to connect to an Oracle database

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 Server.

Page 10: Ch06 ado.net fundamentals

The Connection Class

10

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.

Page 11: Ch06 ado.net fundamentals

The Connection Class cont..

11

For examplestring 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 settingstring 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:\DataSources\Northwind.mdb";

Page 12: Ch06 ado.net fundamentals

The Connection Class cont..

12

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.

Page 13: Ch06 ado.net fundamentals

Testing a Connection

13

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> " +con.State.ToString();

}

Page 14: Ch06 ado.net fundamentals

Connection Pooling

14

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.

Page 15: Ch06 ado.net fundamentals

Connection Pooling cont…

15

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.

Page 16: Ch06 ado.net fundamentals

The Command and DataReader Classes

16

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.

Page 17: Ch06 ado.net fundamentals

Command Basics

17

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 EnumerationValue Description

CommandType.Text The command will execute a direct SQL statement.CommandText property provides SQL statement

CommandType.StoredProcedure

The command will execute a stored procedure in the data source. The CommandText property provides the name of the stored procedure.

CommandType.TableDirect

The command will query all the records in the table. The CommandText is the name of the table from which the command will retrieve the records.

Page 18: Ch06 ado.net fundamentals

Command Basics cont..

18

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;

Page 19: Ch06 ado.net fundamentals

Command object…

19

The Command object provides three methods that you can use to perform the command. Command Methods:

Method DescriptionExecuteNonQuery() 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.

Page 20: Ch06 ado.net fundamentals

The DataReader Class

20

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()

Page 21: Ch06 ado.net fundamentals

The DataReader Class cont..

21

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();...

Page 22: Ch06 ado.net fundamentals

The DataReader Class cont..

22

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();…..

Page 23: Ch06 ado.net fundamentals

Processing Multiple Result Sets

23

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.

Page 24: Ch06 ado.net fundamentals

The ExecuteScalar() Method

24

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 />";

Page 25: Ch06 ado.net fundamentals

The ExecuteNonQuery() Method

25

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{con.Close();}

Page 26: Ch06 ado.net fundamentals

Using Parameterized Commands

26

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.

Page 27: Ch06 ado.net fundamentals

Calling Stored Procedures

27

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 usageThey can improve performance

Page 28: Ch06 ado.net fundamentals

Calling Stored Procedures cont..

28

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

GOCREATE PROCEDURE InsertEmployee

@TitleOfCourtesy varchar(25),@LastName varchar(20),@FirstName varchar(10),@EmployeeID int OUTPUT

ASINSERT INTO Employees

(TitleOfCourtesy, LastName, FirstName, HireDate)VALUES (@TitleOfCourtesy, @LastName, @FirstName,

GETDATE());

SET @EmployeeID = @@IDENTITY

Page 29: Ch06 ado.net fundamentals

Calling Stored Procedures cont..

29

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;

Page 30: Ch06 ado.net fundamentals

Calling Stored Procedures cont..

30

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);