Vous êtes sur la page 1sur 110

ADO.

NET

ADO.NET and the .NET


Framework
Microsoft .NET Framework
Web Services

User Interface

Data and XML


ADO.NET

XML

...

Base Classes
Common Language Runtime

...

ADO vs. ADO.NET


ADO
Designed for connected access
The RecordSet is the central data container
RecordSet is one (1) table that contains all the
data
Retrieving data from > 1 table or source requires a
database JOIN
Data is flattened: lose relationships; navigation is
sequential

Data types are bound to COM/COM+ data types


Data sharing via COM marshalling
Problems marshalling through firewalls (DCOM,
binary)

ADO vs. ADO.NET


ADO.NET
Designed for disconnected access
The DataSet replaces the RecordSet
DataSet can contain multiple tables
Retrieving data from > 1 table or source does not
require a JOIN
Relationships are preserved: navigation is relational

Data types are only bound to XML schema


XML, like HTML, is plaintext: Firewall friendly

Benefits of ADO.NET
Interoperability through use of XML
Open standard for data that describes itself
Human readable text
Used internally but accessible externally
Can use XML to read and write and move data

Scalability through the disconnected


DataSet
Connections are not maintained for long
periods

Maintainability
Separation of data logic and user interface

ADO.NET Architecture Diagram

ADO.NET-related Namespaces
ADO.NET

System.Data

.SqlTypes

.SqlClient

.Common

.OleDb

ADO.NET Namespaces
System.data

Core namespace, defines types that


represent data

System.Data.Common

Types shared between managed providers

System.Data.OleDb

Types that allow connection to OLE DB


compliant data sources

System.Data.SqlClient

Types that are optimized to connect to


Microsoft SQL Server

System.Data.SqlTypes

Native data types in Microsoft SQL Server

Importing the ADO.NET


Namespaces
Needed to build a data access application
For OLE DB:
Imports System.Data
Imports System.Data.OleDB

For SQL Server:


Imports System.Data
Imports System.Data.SQLClient

The (ADO).NET Data Providers


A collection of classes for accessing data
sources:
Microsoft SQL Server 2000, SQL Server 7, and
MSDE
Any OLE Database (OLE DB) providers
Including: Oracle, JET, and SQL OLE DB Providers

Establish connection between DataSets and data


stores

Two .NET data providers:


ADO: via the System.Data.OleDb namespace
SQL Server: via the System.Data.SqlClient
namespace

System.Data.OleDb is the .NET data provider

.NET Data Providers Hierarchy


.Common
Contains classes
shared by both

System.Data
.SqlClient
SqlCommand
SqlConnection
SqlDataReader
SqlDataAdapter

.OleDb
OleDbCommand
OleDbConnection
OleDbDataReader
OleDbDataAdapter

SqlConnection

SqlConnection
Connects to databases.
Two provider-specific classes
SqlConnection
OleDbConnection.

Connections can be opened in two ways:


Explicitly by calling the Open method on the
connection
Implicitly when using a DataAdapter.

Connections handle transactions

SqlConnection
Represent a unique session with a data source
Create, open, close a connection to a data
source
Functionality and methods to perform
transactions
When an instance of SqlConnection is created, the
read/write properties are set to initial values.
String conStr=server=191.1.32.170; database=bali;
uid=sa;pwd=;
SqlConnection aConn = new SqlConnection(conStr);
aConn.Open();
// Execute Queries using SqlCommand Class
aConn.Close();

SqlConnection Constructor
public SqlConnection();
Initializes a new instance of the SqlConnection
class.

public SqlConnection(string);
Initializes a new instance of the SqlConnection
class when given a string containing the
connection string.

SqlConnection Example
using System;
using System.Data.SqlClient;
public class DataBaseConnection {
public static void Main () {
string strCon = server=vas\\vas01; database=pubs;
UID=sa;PWD=shivhari;
SqlConnection objCon1 = new SqlConnection();
objCon1.ConnectionString = strCon
SqlConnection objCon2 = new
SqlConnection(strCon)
objCon1.Open();
objCon2.Open();
System.Console.WriteLine(objCon1.State);
System.Console.WriteLine(objCon2.State);
}
}

SqlConnection-Properties
Property

Description

ConnectionString

Gets or sets the string used to open a SQL Server database.

ConnectionTimeout

Gets the time to wait while trying to establish a connection before


terminating the attempt and generating an error.

Database

Gets the name of the current database or the database to be used


once a connection is open.

DataSource

Gets the name of the instance of SQL Server to which to connect.

PacketSize

Gets the size (in bytes) of network packets used to communicate


with an instance of SQL Server .

ServerVersion

Gets a string containing the version of the instance of SQL Server


to which the client is connected.

State

Gets the current state of the connection.

WorkstationId

Gets a string that identifies the database client.

SQLConnection.ConnectionString
Unlike OLE DB or ADO, the connection string that is
returned is the same as the user-set ConnectionString
minus security information, if Persist Security Info
value is set to false (default).
The SQL Server .NET Data Provider does not persist
or return the password in a connection string unless
you set Persist Security Info to true.

SQLConnection.ConnectionString
The ConnectionString property can be set only when
the connection is closed.
When the connection string is set, all of these
properties are updated, except when an error is
detected. In this case, none of the properties are
updated.
SqlConnection properties return only those settings
contained in the ConnectionString.
Resetting the ConnectionString on a closed
connection resets all connection string values (and
related properties) including the password.

SQLConnection Properties
Connect Timeout / Connection Timeout (15)
The length of time (in seconds) to wait for a
connection to the server before terminating the
attempt and generating an error.
Connection Lifetime(0)
When a connection is returned to the pool, its
creation time is compared with the current time,
and the connection is destroyed if that time span
(in seconds) exceeds the value specified by
connection
lifetime.
Useful
in
clustered
configurations to force load balancing between a
running server and a server just brought on-line.

SQLConnection.Properties
Data Source/Server (null)
The name or network address of the instance of
SQL Server to which to connect.
Initial Catalog / Database (null)
The name of the database.

SQLConnection.Properties
.
Packet Size (8192)
Size in bytes of the network packets used to
communicate with an instance of SQL Server.
Password /Pwd ()
The password for the SQL Server account logging
on.
Pooling ('true)
When true, the SQLConnection object is drawn
from the appropriate pool, or if necessary, is
created and added to the appropriate pool.

Intro to Connection Pooling


The SQL Server .NET Data Provider relies on Windows
2000 Component Services to provide connection
pooling using an implicit pooling model by default.
The SqlConnection object also has connection string
modifiers that you can set to control implicit pooling
behavior, facilitating

Pool Creation and Assignment

Connection Addition

Connection Removal

Support for Transactions

Controlling Pooling using ConnectionString

Intro to Connection Pooling


Pool Creation and Assignment
Each connection pool is associated with one distinct
connection string, using an exact matching
algorithm.
If no exact match is found, a new pool is created.
Once created, connection pools are not destroyed
until the active process ends. Maintenance of inactive
or empty pools involves minimal system overhead.

Intro to Connection Pooling


Connection Addition
A connection pool is created for each unique connection
string.
When a pool is created, multiple connection objects are
created and added to the pool so that the minimum pool
size requirement is satisfied.
Connections are added to the pool as needed, up to the
maximum pool size.
When a SqlConnection object is requested, it is obtained
from the pool if a usable connection is available.
A usable connection is one that must be currently
unused and have a valid link to the server.

Connection Pooling
When the maximum pool size is reached, the
request is queued.
The object pooler satisfies these requests by
reallocating connections as they are released back
into the pool.
If the time-out period (determined by the Connect
Timeout connection string property) elapses before
a connection object can be obtained, an error
occurs.
You must always close the Connection when you are
finished using it.

Connection Pooling
Connection Removal
The object pooler will remove a connection from the
pool if the connection lifetime has expired, or if the
pooler detects that the connection with the server
has been severed.
This can be detected only after attempting to
communicate with the server. If a connection is
found that is no longer connected to the server, it is
marked as invalid.
The object pooler periodically scans connection
pools looking for objects that have been released to
the pool and are marked as invalid.
These connections are then permanently removed.

Connection Pooling
Connection Removal
It is possible for an apparently valid connection to
be drawn from the pool although the associated
server has disappeared.
When this occurs, an exception is generated.
However, the user must still close the connection to
release it back into the pool.

Connection Pooling
Controlling Connection Pooling with Connection String
Keywords
Max Pool Size(100) - Min Pool Size(0)
Pooling('true)
When true, the SQLConnection object is drawn
from the appropriate pool, or if necessary,
created and added to the appropriate pool.

SQLConnection Methods

Open

Opens a database connection with the property


settings specified by the ConnectionString.

Close

Closes the connection to the database. This is the


preferred method of closing any open connection.

ChangeDatabase

Changes the current


SqlConnection.

CreateCommand

Creates and returns a SqlCommand


associated with the SqlConnection.
Overloaded. Begins a database transaction.

BeginTransaction

database

for

an

open
object

SqlConnection.Open() Method
Opens a database connection with the property settings
specified by the ConnectionString.
public void Open();
Exceptions
An SqlException would be thrown if a connection-level
error occurs while opening a connection.
An InvalidOperationException would be thrown if the
data source or server is not specified or if the
connection is already open.
The SqlConnection draws an open connection from the
connection pool if one is available.
Otherwise, it establishes a new connection to an instance of
SQL Server.

SqlConnection.Close()
Closes the connection to the database. This is the preferred
method of closing any open connection.
public void Close();
Exceptions
An SqlException would be thrown if a connection-level
error occurs while closing a connection.
The Close method rolls back any pending transactions. It then
releases the connection to the connection pool, or closes the
connection if connection pooling is disabled.
An application can call Close more than one time. No
exception is generated.

SqlConnection.ChangeDatabase() Method
Changes the current database for an open SqlConnection.
public void ChangeDatabase( string database );
Exceptions
ArgumentException Invalid DataBase name
InvalidOperationException -The connection is not open.
SqlException - Cannot change databases.

The value supplied in the database parameter must be a valid


database name.
The database parameter cannot contain a null value, be
empty, or contain a string with only blank characters.

SqlConnection.CreateCommand()

Creates and returns a SqlCommand object associated with


the SqlConnection.
public SqlCommand CreateCommand();

SqlConnection.BeginTransaction()

Begins a database
SqlTransaction object.

transaction

and

returns

OverLoads public SqlTransaction BeginTransaction();


public SqlTransaction BeginTransaction(IsolationLevel);
public SqlTransaction BeginTransaction(string);
public SqlTransaction BeginTransaction(IsolationLevel,
string);

an

SqlConnection.BeginTransaction()
SqlConnection objCon1 = new SqlConnection(strCon);
ObjCon1.Open();
SqlCommand objCmd1= new SqlCommand();
SqlTransaction objTran1;

// Start a local transaction


objTran1 =
objCon1.BeginTransaction(IsolationLevel.ReadCommitted,"Tran1");

// Assign transaction object for a pending local transaction

objCmd1.Transaction = objTran1;
Cont.

SqlConnection.BeginTransaction()
try {
objCmd1.CommandText = "Insert into Region (RegionID, RegionDescription)
VALUES (100, 'Description')";
objCmd1.ExecuteNonQuery();
objCmd1.CommandText = "Insert into Region (RegionID, RegionDescription)
VALUES (101, 'Description')";
objCmd1.ExecuteNonQuery();
objTran1.Commit();
Console.WriteLine("Both records are written to database.");
}

Cont.

SqlConnection.BeginTransaction()
catch(Exception ex)
{
objTran1.Rollback("Tran1");
Console.WriteLine(ex.ToString());
Console.WriteLine("Neither record was written to database.");
}
finally
{
// close the connection after Committing or Rolling back
objCon1.Close();
}
}

SqlTransaction Class
Represents a Transact-SQL transaction to be made in
a SQL Server database. This class cannot be inherited
Implementation
public sealed class SqlTransaction :
MarshalByRefObject, IDbTransaction, IDisposable
The application creates a SqlTransaction object by
calling BeginTransaction on the SqlConnection
object.
All subsequent operations associated with the
transaction (for example, committing or aborting the
transaction), are performed on the SqlTransaction
object.

SqlTransaction.IsolationLevel Property
The isolation level is measure of the extent to which changes made
outside a transaction are visible inside that transaction.

Specifies the IsolationLevel for this transaction.


The IsolationLevel
ReadCommitted.

for

this

transaction.

Parallel transactions are not supported.


IsolationLevel applies to the entire transaction.

The

default

Therefore,

is
the

IsolationLevel Enumeration
The IsolationLevel remains in effect until explicitly changed, but
it can be changed at any time.
The new value is used at execution time, not parse time. If
changed during a transaction, the expected behavior of the
server is to apply the new locking level to all statements
remaining.

IsolationLevel Enum
Chaos

The pending changes from more highly isolated


transactions cannot be overwritten.

ReadCommitted

Shared locks are held while the data is being read


to avoid dirty reads.

ReadUncommitt
ed

A dirty read is possible -- no shared locks are


issued and no exclusive locks are honored.

RepeatableRead Locks are placed on all data that is used in a query,


preventing other users from updating the data.

Dirty Reads

Some row in a table

Processing Sequence:
A writes a value out
B reads the value in
A does a rollback (restoring the original value)
Consequence:
B has performed a dirty read
B has an incorrect value

Processing Sequence:

Some row in a table

Non Repeatable Reads

B reads a value in
A writes the value out
A does a commit (making its change permanent)

Consequence
B has performed a non-repeatable read
B has the wrong value
If B rereads, it will get a different value

Processing Sequence:
A reads a set of rows in
B writes a row that would
been in As set, had B been
quicker.

have

Consequence
A doesnt have the data it thought
it had
If A performs the same query,
phantoms (new records) will appear

Asetofrowsinatable

Phantom Reads
A

SqlTransaction.Commit() Method Property


Commits the database transaction
An Exception is thrown when it is not possible to commit a
transaction
The Commit method is equivalent to the T-SQL COMMIT
TRANSACTION statement.
What about Nested Transactions??
Committing inner transactions is ignored by Microsoft SQL Server.
The transaction is either committed or rolled back based on the
action taken at the end of the outermost transaction.
If the outer transaction is committed, the inner nested transactions
are also committed.
If the outer transaction is rolled back, then all inner transactions are
also rolled back, regardless of whether or not the inner transactions
were individually committed.

SqlTransaction.Rollback() Method
Rolls back a transaction from a pending state.
public void Rollback();
public void Rollback(string);

SqlTransaction.Save() Method
Creates a savepoint in the transaction that can be used to roll
back a portion of the transaction, and specifies the savepoint
name.
public void Save( string savePointName);
Exception
InvalidOperationException is thrown
If this transaction is already committed
(or)
The connection is broken

SqlTransaction.Save() Method
Savepoints offer a mechanism to roll back portions of
transactions.
You create a savepoint using the Save method, and then
later call the Rollback method to roll back to the savepoint
instead of rolling back to the start of the transaction.

SqlCommand

SqlCommand
Information submitted to a database as a query via a
Connection object
Two provider-specific classes
SqlCommand
OleDbCommand

Input and output parameters are supported, along


with return values as part of the command syntax
Results are returned in the form of streams.
Accessed by:
DataReader object
DataSet object via a DataAdapter

SQLCommand Class
Represents a T-SQL command or a Stored
Procedure call
Different methods to execute record-returning
queries and non-query statements.
ExecuteNonQuery() No Data Returned
ExecuteReader(,) - Result set captured into DataReader
ExecuteScalar() First column of first row
ExecuteXmlReader() Builds XmlReader

SQLCommand constructors
public SqlCommand();

public SqlCommand(string);

public SqlCommand(string, SqlConnection);

public SqlCommand(string, SqlConnection, SqlTransaction);

SQLCommand Example
public void CreateSqlCommandDemo() {
SqlConnection objCon1 = new SqlConnection("user
id=sa;password=;initial catalog=northwind;data
source=demoSQLServer");
objCon1.Open();
SqlTransaction objTran1 = objCon1.BeginTransaction();
string strSelectQuery = "SELECT * FROM Categories ORDER
BY CategoryID";
SqlCommand objCmd1 = new SqlCommand(strSelectQuery,
objCon1,objTran1);
objCmd1.CommandTimeout = 20;
}

SQLCommand Properties
Connection

Gets or sets the SqlConnection used by this


instance of the SqlCommand.

CommandTimeout Gets or sets the wait time before terminating

the attempt to execute a command and


generating an error.
CommandText

Gets or sets the Transact-SQL statement or


stored procedure to execute at the source.

CommandType

Gets or sets a value indicating how the


CommandText property is to be interpreted.

Transaction

Gets or sets the transaction in which the


SqlCommand executes

Parameters

Gets the SqlParameterCollection.

SQLCommand Example
public void CreateMySqlCommandDemo() {
SqlCommand objCmd1 = new SqlCommand();
objCmd1.CommandText = "SELECT * FROM Categories
ORDER BY CategoryID";
objCmd1.CommandTimeout = 15;
objCmd1.CommandType = CommandType.Text;
}
CommanType Enum
Text
StoredProcedure
TableDirect

SqlCommand Methods
ExecuteNonQuery

Executes a Transact-SQL statement against the


Connection and returns the number of rows affected.

ExecuteReader

Overloaded. Sends the CommandText


Connection and builds a SqlDataReader.

ExecuteScalar

Executes the query, and returns the first column of the


first row in the resultset returned by the query.

ExecuteXmlReader

Sends the CommandText to the Connection and


builds an XmlReader object.

Cancel

Cancels the execution of a SqlCommand.

CreateParameter

to

Creates a new instance of a SqlParameter object.

Prepare

Creates a prepared version of the command.

ResetCommandTimeout

Resets the CommandTimeout property default.

the

SqlCommand.ExecuteNonQuery()
Executes a Transact-SQL statement against the Connection
and returns the number of rows affected.
public int ExecuteNonQuery();
Usage Scenarios :

To perform catalog operations.

To change the data in a database without using a


DataSet by executing UPDATE, INSERT, or DELETE
statements.

Although the ExecuteNonQuery does not return any


rows, any output parameters.

SqlCommand.ExecuteReader()
Sends the CommandText to the Connection and builds a
SqlDataReader.
public SqlDataReader ExecuteReader();
public SqlDataReader
ExecuteReader(CommandBehavior);
CommandBehavior Enumeration

Specifies a description of the results and the


effect on the database of the query command.

This enumeration has a FlagsAttribute that allows


a bitwise combination of its member values.

CommandBehaviour Enum
CloseConnection

When the command is executed, the


associated Connection object is closed when
the associated DataReader object is closed.

SchemaOnly

The query returns column information only


and does not affect the database state.

SequentialAccess

The results of the query are read sequentially


to the column level. This allows an application
to read large binary values using the GetChars
or GetBytes methods of a .NET data provider.
Execution of the query may affect the database
state.

SqlCommand.ExecuteReader()
Method strSelectQuery,string
public void CreateSqlDataReaderDemo(string
strCon) {
SqlConnection objCon1 = new SqlConnection(strCon);
SqlCommand objCmd1 = new SqlCommand(strSelectQuery, objCon1);
objCmd1.Connection.Open();
SqlDataReader objDataReader =
objCmd1.ExecuteReader(CommandBehavior.CloseConnection);
while(objDataReader.Read())
{
Console.WriteLine(objDataReader.GetString(0));
}
objDataReader.Close();
//objCon1.Close();}

SqlCommand.ExecuteScalar()
Executes the query, Method
and returns the first column of

the
first row in the resultset returned by the query. Extra
columns or rows are ignored.
public object ExecuteScalar();

Usage Scenarios
To retrieve a single value (aggregate) from a database.
Less code in this case that DataReader
Formatting :
objCmd1.CommandText
=
"select
NumberOfRegions from region";
Int count = (int) objCmd1.ExecuteScalar();

count(*)

as

SqlCommand.ExecuteXmlReader()
Sends the CommandText to the Connection and builds an
XmlReader object.
public XmlReader ExecuteXmlReader();
Usage Scenarios:
Transact-SQL a valid FOR XML clause

Formatting:
SqlCommand mySqlCommand = new
SqlCommand("select * from customers FOR XML
AUTO, mySqlConnection);

SqlCommand.Methods
SqlCommand.Cancel()
Cancels the execution of a SqlCommand .
public void Cancel();
SqlCommand.CreateParameter()
public SqlParameter CreateParameter();
SqlCommand.Prepare()

If the CommandType property is set to TableDirect,


Prepare does nothing.

If CommandType is set to StoredProcedure, the call


to Prepare should succeed, although it may result in
a no-op.

SqlParameter

SqlParameter Class
Represents a parameter to a SqlCommand,
optionally, its mapping to DataSet columns.
This class cannot be inherited.
Parameter names are not case sensitive.

and

SqlParameter.ParameterName
Property

Gets or sets the name of the SqlParameter


The ParameterName
@paramname.

is

specified

in

the

form

You must set ParameterName before executing a


SqlCommand that relies on parameters.
public void CreateSqlParameterExample() {
SqlParameter myParameter = new SqlParameter();
myParameter.ParameterName = "@Description";
myParameter.IsNullable = true;
myParameter.DbType = DbType.String;
myParameter.Direction =
ParameterDirection.Output; }

SqlParameter.DbType & SqlDbType


Property
DbType
Gets or sets the DbType of the parameter
The SqlDbType and DbType are linked. Therefore,
setting the DbType changes the SqlDbType to a
supporting SqlDbType.
SqlDbType

Gets or sets the SqlDbType of the parameter

SqlParameter.Direction Property
Gets or sets a value indicating whether the parameter
is input-only, output-only, bidirectional, or a stored
procedure return value parameter.
public ParameterDirection Direction {get; set;}
ParameterDirection Enum
Input
InputOutput
Output
ReturnValue

The parameter is an input


parameter.
The parameter is capable of
both input and output.
The parameter is an output
parameter.
The parameter represents a return
value from an operation such as a
stored
procedure,
built-in
function, or user-defined function.

SqlParameter.Size Property
Gets or sets the maximum size, in bytes, of the data
within the column.
The default value is inferred from the the parameter
value.
The Size property is used for binary and string types.
For nonstring data types and ANSI string data, Size
refers to the number of bytes.
For Unicode string data, Size refers to the number of
characters.
The count for strings
terminating character.

does

not

include

the

SqlParameter.Precision & Scale


Property

Precision

Gets or sets the maximum number of digits used to


represent the Value property for Decimal datatypes.
Scale:
The number of decimal places to which Value is
resolved. The default is 0.
public void CreateSqlParameterDemo() {
SqlParameter myParameter = new SqlParameter("@Price",
SqlDbType.Decimal);
myParameter.Value = 3.1416;
myParameter.Precision = 8;
myParameter.Scale = 4; }

SqlParameters Collection

SqlParametersCollection Class
Collects all parameters relevant to a SqlCommand as well as their
respective mappings to Dataset Columns.

Count
Item

Gets the number of SqlParameter objects in the collection.

Overloaded, Gets the SqlParameter with a specified attribute.


public SqlParameter this[int] {get; set;} --- Index
public SqlParameter this[string] {get; set;}---parameter name

SqlParametersCollection Methods
Method
Add
Insert
Remove
RemoveAt
Clear
Contains
IndexOf

Description
Overloaded. Adds a SqlParameter to the
SqlParameterCollection.
Inserts a SqlParameter in the collection
at the specified index.
Removes the specified SqlParameter
from the collection.
Overloaded. Removes the specified
SqlParameter from the collection.
Removes all items from the collection.
Overloaded.
Indicates
whether
a
SqlParameter exists in the collection.
Overloaded. Gets the location of a
SqlParameter in the collection.

SqlParametersCollection.Add()
Method

public SqlParameter Add(SqlParameter);

public SqlParameter Add(string, SqlDbType, int);


myDataAdapter.SelectCommand.Parameters.Add("@CategoryName
", SqlDbType.VarChar, 80).Value = "toasters";
myDataAdapter.SelectCommand.Parameters.Add("@SerialNum"
, SqlDbType.Int).Value = 239;

SqlParametersCollection.Insert()
Method

Inserts a SqlParameter in the collection at the


specified index.
public void Insert( int index, object value);

SqlParametersCollection.Remove()
Method

Removes the
collection.

specified

SqlParameter

from

the

public void Remove( object value);


Exceptions

An InvalidCastException would be thrown if the


parameter is not a SqlParameter.

A SystemException would be thrown if the parameter


does not exist in the collection.

SqlParametersCollection.RemoveAt()
Removes the
collection.

specified

SqlParameter

from

public void RemoveAt(int); -- Parameter Index


public void RemoveAt(string); - Parameter Name

the

SqlParametersCollection.CopyTo()
Copies
SqlParameter
objects
from
SqlParameterCollection to the specified array.
public void CopyTo( Array array, int index );
SqlParameter[] myParamArray = new
SqlParameter[myCmd.Parameters.Count - 1];
myCmd.Parameters.CopyTo(myParamArray, 0);

the

SqlParametersCollection.Clear()
Method

Removes all items from the collection.


public void Clear();
public bool ExportAndClear() {
// ...

// create SqlCommand myCmd

// ...

SqlParameter[] myParamArray = new


SqlParameter[myCmd.Parameters.Count - 1];
myCmd.Parameters.CopyTo(myParamArray, 0);
myCmd.Parameters.Clear();
return true;
}

SqlParametersCollection.Contains()
Indicates whether a SqlParameter exists in the
collection.
OverLoads
public bool Contains(object);
public bool Contains(string);

SqlParametersCollection.IndexOf()
Gets the location of a SqlParameter in the collection.
OverLoads:
public int IndexOf(object);
public int IndexOf(string);
public void SearchForSqlParams() {
// ...

// create SqlCommand myCmd

// ...

if (!objCmd.Parameters.Contains("Description"))
System.Console.WriteLine("ERROR: no such parameter in the
collection");
else
System.Console.WriteLine("match on parameter #" +
objCmd.Parameters.IndexOf("Description").ToString()); }

SqlDataReader

SqlDataReader
Forward-only data access
Lightweight programming model
Less overhead than using SqlDataAdapter

Instantiated & returned by


SqlCommand.ExecuteReader

SqlDataReaderClass

Provides a means of reading a forward-only tablulardata-stream(TDS) of rows from a SQL Server database.

Akin to a ForwardOnly, ReadOnly, Connection-based


ADO Recordset

Created during a successful call to the ExecuteReader


method of the SqlCommand object, rather than directly
using a constructor.

While the SqlDataReader is in use, the associated


SqlConnection is busy serving the SqlDataReader,

No other operations can be performed on the


SqlConnection other than closing it.

This is the case until the Close method of the


SqlDataReader is called.

SqlDataReaderClass Properties
Property

Description

Field Count

Gets the number of columns in the current row.

Is Closed

Gets a value indicating whether the data reader is closed.

Item

Overloaded. Gets the value of a column in its native format.

Records
Affected

Gets the number of rows changed, inserted, or deleted by


execution of the Transact-SQL statement.

ADO.NET SqlDataReaderClass.Close() Methods

Closes the SqlDataReader object.

You must explicitly call the Close method when you are
through using the SqlDataReader to use the associated
SqlConnection for any other purpose.

SqlConnection myConnection = new


SqlConnection(myConnString);
SqlCommand myCommand = new
SqlCommand(mySelectQuery,myConnection);
myConnection.Open();
SqlDataReader myReader;
myReader = myCommand.ExecuteReader();
// Always call Read before accessing data. while
(myReader.Read()) { Console.WriteLine(myReader.GetInt32(0)
+ ", " + myReader.GetString(1)); }
// always call Close when done reading. myReader.Close();

SqlDataReader.IsDbNull() Method

Gets a value indicating whether the column contains


non-existent or missing values.

public bool IsDBNull( int i);


The parameter is the zero-based column ordinal.

SqlDataReader.Read() Method

Advances the SqlDataReader to the next record.

public bool Read();


The default position of the SqlDataReader is prior to the
first record. Therefore, you must call Read to begin
accessing any data.
While the SqlDataReader is in use, the associated
SqlConnection is busy serving it until you call Close.

SqlDataAdapter

SqlDataAdapter Class
Bridge between the DataSet and the
data store
Inherited from the DataAdapter class

Means to modify the DataSet and data


source

data store

DataAdapter

DataSet

SqlDataAdapter class
Represents a set of data commands and a database
connection which are used to fill the DataSet and update a
SQL Server database.
The SqlDataAdapter, serves as a bridge between a DataSet
and SQL Server for retrieving and saving data.
The SqlDataAdapter provides this bridge by mapping Fill,
which changes the data in the DataSet to match the data in
the data source
Update, which changes the data in the data source to match
the data in the DataSet, using the appropriate Transact-SQL
statements against the data source .
The SqlDataAdapter also includes the SelectCommand,
InsertCommand, DeleteCommand, UpdateCommand, and
TableMappings properties for facilitating the loading and
updating of data

SqlDataAdapter Constructor
public SqlDataAdapter();

public SqlDataAdapter(SqlCommand);
public SqlDataAdapter(qrystring, SqlConnection);

SqlDataAdapter Properties
Property

Description

SelectCommand

Gets or sets a Transact-SQL statement


used to select records in the data source.

InsertCommand

Gets or sets a Transact-SQL statement to


insert new records into the data source.

DeleteCommand

Gets or sets a Transact-SQL statement to


delete records from the data set.

Gets or sets a Transact-SQL statement


used to update records in the data
source.
TableMappings (inherited from Gets a collection that provides the master
DataAdapter)
mapping between a source table and a
DataTable.
UpdateCommand

SqlDataAdapter Methods
Fill (inherited from
DbDataAdapter)

Adds or refreshes rows in the DataSet to


match those in the data source.

Update (inherited from


DbDataAdapter)

Overloaded. Calls the respective INSERT,


UPDATE, or DELETE statements for each
inserted, updated, or deleted row in the
DataSet from a DataTable named
"Table".

SqlDataAdapter.Update() Method
public int Update(DataRow[]);
public override int Update(DataSet);
public int Update(DataTable);

System.Data Namespace
Contains the basis and bulk of ADO.NET
Data-centric namespace
Provides the means to work on and with
your data!

Classes and methods to manipulate your data


Ability to create views of your data
Means to logically represent your data
Enables the use of XML to view, share, and
store data

Introducing the Objects


System.Data
DataSet
DataTable
DataRow
DataColumn
DataRelation
DataViewManager

Contains the main classes of ADO.NET


In-memory cache of data
In-memory cache of a database table
Used to manipulate a row in a DataTable
Used to define the columns in a DataTable
Used to relate 2 DataTables to each other
Used to create views on DataSets

Putting the Objects Together


DataSet

Tables
DataTable

DataView

DataRow(s)

Relations
DataRelation

DataColumn
Constraint(s)

DataRelation
DataTable
DataTable

DataViewManager

Working Data - The DataSet


An in-memory cache of data from a data source
Common way to represent and manipulate data
Universal data container
Not just for use with databases

Designed to be disconnected from the data


source
Connect, execute query, disconnect

Can use XML


To read and write data
To read and write XMLSchema

Properties & Methods of Interest


Collections are used to add & remove tables &
relations
Properties of Interest:
Tables: Returns the collection of DataTable objects
Relations: Returns the collection of DataRelations
Namespace: Gets or sets the namespace of the
DataSet

Using Properties Samples:


myDataSet.Tables.Add( myTable );
myDataTableCollection = myDataSet.Tables

All About Data!


Universal Data Container

DataSet: Its not just for Databases

The DataTable
May be mapped to a physical table in the data
source
Can be related to one another through
DataRelations
Optimistic concurrency or locking - model
Properties of Interest:
Columns: Returns ColumnsCollection of
DataColumns
Rows: Returns DataRow objects as a RowsCollection
ParentRelations: Returns the RelationsCollection
Constraints: Returns the tables ConstraintsCollection
DataSet: Returns the DataSet of the DataTable
PrimaryKey: Gets the DataColumns that make up the
tables primary key

DataSet and DataTable


Create a DataTable and add it to a DataSet

DataSet ds = new DataSet();


// Create DataTable object: Customers.
DataTable dt= new DataTable( Customers );
// Create and add columns to the table
// 1. Explicitly create and Add a DataColumn
DataColumn dc;
dc = new DataColumn( CustID, Type.GetType("System.Int16"));
dt.Columns.Add( dc );
// 2. Implicitly Create and Add columns (DataColumn).
dt.Columns.Add( First_Name,Type.GetType("System String));
dt.Columns.Add( Last_Name, Type.GetType("System String));
// Add the DataTable object to the DataSet
ds.Tables.Add( dt );

Relating Data - The DataRelation


Used to create logical relations between your data
Create relations between two (2) DataTable objects
Requires a DataColumn object from each DataTable
The DataType of both DataColumns must be the same
Cannot relate a Int32 DataColumn and a String
DataColumn
The relation is named (by you!)
DataRelation dr=new
DataRelation( myRelation,...)

Makes relational navigation possible


RelationsCollection used to hold/group them
Accessed through the DataSets Relations property

Creating Relations With


DataRelations
// Building on the DataTable example earlier...
// Get the DataTable DataColumns we want to relate...
DataColumn parentCol, childCol;
parentCol= DataSet.Tables["Customers"].Columns["CustID"];
childCol = DataSet.Tables["Orders].Columns["CustID"];
// Create DataRelation with the name CustomerOrders...
DataRelation dr = new DataRelation("CustomersOrders",
parentCol,
childCol);
// Add the relation to the DataSet...
ds.Relations.Add( dr );

XML and the DataSet


DataSet can read/write XML for its data and/or
schema
You can create or modify data in a DataSet using XML
You can create or modify the DataSets schema using
XML

XML-related DataSet methods for reading:


ReadXml: Reads an XML schema and data into the
DataSet
ReadXmlSchema: Reads an XML schema into the
DataSet

And for writing:


WriteXml, WriteXmlSchema
GetXml, GetXmlSchema

Namespace property: sets the namespace for


serialization

Methods of Reading and Writing XML


// Code for creating the DataSet mds and loading the
// DataSet from a data source not shown.
String oFile = C:\\My_ADO.NET\\myXmlOutput.xsd;
String iFile = C:\\My_ADO.NET\\myXmlInput.xsd;
// Write the DataSets XMLSchema to an XML Document
mds.WriteXmlSchema( oFile );
// Read/Upload XML Data into the DataSet
mds.ReadXml( iFile);
// modify the data
// ...
// Write the existing Data to an XML Document
mds.WriteXml( "C:\\My_ADO.NET\\myXmlData.txt",
XmlWriteMode.DiffGram);

Viewing Data - The DataView


Create multiple views on DataTable objects
Bindable to user interface controls
Properties of Interest:
Table: Retrieves or sets the associated
DataTable
Sort: Gets or sets the tables sort
columns and sort order

Creating a DataView
// Code for myTable Customers with Name column not shown
DataView view1 = new DataView( myTable );
DataView view2 = new DataView( myTable );
// Creates Ascending view of Customers by Name
view1.Sort = Name ASC;
// Bind to UI element(s)...
DataGrid myGrid = new DataGrid();
myGrid.SetDataBinding( view1, Customer);
//...

Summary

ADO.NET is the evolution of ADO


It is a disconnected, Web-centric model
Flexible in its ability to work with data
Increases your ability to logically organize
data
Extensive support for XML
Facilitates working with and sharing data

Interacts with a wide variety of data sources

Vous aimerez peut-être aussi