Top Banner
ADO.NET
110
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: ADO1

ADO.NETADO.NET

Page 2: ADO1

ADO.NET and the .NET Framework

ADO.NET and the .NET Framework

Microsoft .NET Framework

Common Language Runtime

Base Classes

Web Services User Interface

Data and XML

ADO.NET XML ... ...

Page 3: ADO1

ADO vs. ADO.NET 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– 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)

Page 4: ADO1

ADO vs. ADO.NET 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”

• 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”

Page 5: ADO1

Benefits of ADO.NETBenefits 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

• 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

Page 6: ADO1

ADO.NET Architecture DiagramADO.NET Architecture Diagram

Page 7: ADO1

ADO.NET

ADO.NET-related NamespacesADO.NET-related Namespaces

System.Data

.OleDb.SqlClient.SqlTypes .Common

Page 8: ADO1

ADO.NET NamespacesADO.NET NamespacesSystem.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

Page 9: ADO1

Importing the ADO.NET Namespaces

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

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

Page 10: ADO1

The (ADO).NET Data ProvidersThe (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

• 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

Page 11: ADO1

.NET Data Providers Hierarchy.NET Data Providers Hierarchy

System.Data

.OleDb.SqlClient

OleDbCommandOleDbConnectionOleDbDataReaderOleDbDataAdapter

SqlCommandSqlConnectionSqlDataReader

SqlDataAdapter

.Common Contains classes shared by both

Page 12: ADO1

SqlConnection

Page 13: ADO1

SqlConnectionSqlConnection

• Connects to databases. • Two provider-specific classes

SqlConnection OleDbConnection.

• Connections can be opened in two ways:Explicitly by calling the Open method on the

connectionImplicitly when using a DataAdapter.

• Connections handle transactions

• Connects to databases. • Two provider-specific classes

SqlConnection OleDbConnection.

• Connections can be opened in two ways:Explicitly by calling the Open method on the

connectionImplicitly when using a DataAdapter.

• Connections handle transactions

Page 14: ADO1

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

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

String conStr=“server=191.1.32.170; database=bali; uid=sa;pwd=”;SqlConnection aConn = new SqlConnection(conStr);aConn.Open(); // Execute Queries using SqlCommand ClassaConn.Close();

Page 15: ADO1

SqlConnection Constructor 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.

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.

Page 16: ADO1

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 = strConSqlConnection objCon2 = new SqlConnection(strCon)objCon1.Open();

objCon2.Open();System.Console.WriteLine(objCon1.State);System.Console.WriteLine(objCon2.State);

}}

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 = strConSqlConnection objCon2 = new SqlConnection(strCon)objCon1.Open();

objCon2.Open();System.Console.WriteLine(objCon1.State);System.Console.WriteLine(objCon2.State);

}}

SqlConnection ExampleSqlConnection Example

Page 17: ADO1

SqlConnection-PropertiesSqlConnection-Properties

PropertyProperty DescriptionDescription

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

ConnectionTimeoutConnectionTimeout Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error.Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error.

DatabaseDatabase Gets the name of the current database or the database to be used once a connection is open.Gets the name of the current database or the database to be used once a connection is open.

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

PacketSizePacketSize Gets the size (in bytes) of network packets used to communicate with an instance of SQL Server .Gets the size (in bytes) of network packets used to communicate with an instance of SQL Server .

ServerVersionServerVersion Gets a string containing the version of the instance of SQL Server to which the client is connected.Gets a string containing the version of the instance of SQL Server to which the client is connected.

StateState Gets the current state of the connection.Gets the current state of the connection.

WorkstationIdWorkstationId Gets a string that identifies the database client.Gets a string that identifies the database client.

Page 18: ADO1

SQLConnection.ConnectionStringSQLConnection.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.

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.

Page 19: ADO1

SQLConnection.ConnectionStringSQLConnection.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.

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.

Page 20: ADO1

SQLConnection PropertiesSQLConnection 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.

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.

Page 21: ADO1

SQLConnection.PropertiesSQLConnection.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.

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.

Page 22: ADO1

SQLConnection.PropertiesSQLConnection.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.

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.

Page 23: ADO1

Intro to Connection PoolingIntro 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

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

Page 24: ADO1

Intro to Connection PoolingIntro 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.

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.

Page 25: ADO1

Intro to Connection PoolingIntro 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 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.

Page 26: ADO1

Connection PoolingConnection 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.

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.

Page 27: ADO1

Connection PoolingConnection 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 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.

Page 28: ADO1

Connection PoolingConnection 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 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.

Page 29: ADO1

Connection PoolingConnection 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.

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.

Page 30: ADO1

SQLConnection MethodsSQLConnection Methods

OpenOpen Opens a database connection with the property settings specified by the ConnectionString.Opens a database connection with the property settings specified by the ConnectionString.

CloseClose Closes the connection to the database. This is the preferred method of closing any open connection.Closes the connection to the database. This is the preferred method of closing any open connection.

ChangeDatabaseChangeDatabase Changes the current database for an open SqlConnection.Changes the current database for an open SqlConnection.

CreateCommandCreateCommand Creates and returns a SqlCommand object associated with the SqlConnection.Creates and returns a SqlCommand object associated with the SqlConnection.

BeginTransactionBeginTransaction Overloaded. Begins a database transaction.Overloaded. Begins a database transaction.

Page 31: ADO1

SqlConnection.Open() MethodSqlConnection.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.  

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.  

Page 32: ADO1

SqlConnection.Close()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.

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.

Page 33: ADO1

SqlConnection.ChangeDatabase() MethodSqlConnection.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.

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.

Page 34: ADO1

SqlConnection.CreateCommand()SqlConnection.CreateCommand()

Creates and returns a SqlCommand object associated with the SqlConnection.

public SqlCommand CreateCommand();  

Creates and returns a SqlCommand object associated with the SqlConnection.

public SqlCommand CreateCommand();  

Page 35: ADO1

SqlConnection.BeginTransaction()SqlConnection.BeginTransaction()

Begins a database transaction and returns an SqlTransaction object.

OverLoads -

public SqlTransaction BeginTransaction();

public SqlTransaction BeginTransaction(IsolationLevel);  

public SqlTransaction BeginTransaction(string);

public SqlTransaction BeginTransaction(IsolationLevel, string);

Begins a database transaction and returns an SqlTransaction object.

OverLoads -

public SqlTransaction BeginTransaction();

public SqlTransaction BeginTransaction(IsolationLevel);  

public SqlTransaction BeginTransaction(string);

public SqlTransaction BeginTransaction(IsolationLevel, string);

Page 36: ADO1

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

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

Page 37: ADO1

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

}

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

Page 38: ADO1

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

}

}

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

}

}

Page 39: ADO1

SqlTransaction ClassSqlTransaction 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.

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.

Page 40: ADO1

SqlTransaction.IsolationLevel PropertySqlTransaction.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 for this transaction. The default is ReadCommitted.

Parallel transactions are not supported. Therefore, the IsolationLevel applies to the entire transaction.

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.

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 for this transaction. The default is ReadCommitted.

Parallel transactions are not supported. Therefore, the IsolationLevel applies to the entire transaction.

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.

Page 41: ADO1

IsolationLevel EnumIsolationLevel Enum

ChaosChaos The pending changes from more highly isolated transactions cannot be overwritten.The pending changes from more highly isolated transactions cannot be overwritten.

ReadCommitted ReadCommitted Shared locks are held while the data is being read to avoid dirty reads.Shared locks are held while the data is being read to avoid dirty reads.

ReadUncommittedReadUncommitted

A dirty read is possible -- no shared locks are issued and no exclusive locks are honored.A dirty read is possible -- no shared locks are issued and no exclusive locks are honored.

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

preventing other users from updating the data. Locks are placed on all data that is used in a query,

preventing other users from updating the data.

Page 42: ADO1

Dirty ReadsDirty Reads

• 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:– 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

A

B

ASom

e ro

w in

a t

able

Page 43: ADO1

Non Repeatable ReadsNon Repeatable Reads

• Processing Sequence:– 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:– 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

B

A

ASom

e ro

w in

a t

able

Page 44: ADO1

Phantom ReadsPhantom Reads

• Processing Sequence:– A reads a set of rows in– B writes a row that would have

been in A’s set, had B been quicker.

• Consequence– A doesn’t have the data it thought

it had– If A performs the same query,

phantoms (new records) will appear

• Processing Sequence:– A reads a set of rows in– B writes a row that would have

been in A’s set, had B been quicker.

• Consequence– A doesn’t have the data it thought

it had– If A performs the same query,

phantoms (new records) will appear

A

B

A s

et o

f ro

ws

in a

tabl

e

Page 45: ADO1

SqlTransaction.Commit() Method PropertySqlTransaction.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.

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.

Page 46: ADO1

SqlTransaction.Rollback() MethodSqlTransaction.Rollback() Method Rolls back a transaction from a pending state.

public void Rollback();

public void Rollback(string);

Rolls back a transaction from a pending state.

public void Rollback();

public void Rollback(string);

Page 47: ADO1

SqlTransaction.Save() MethodSqlTransaction.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

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

Page 48: ADO1

SqlTransaction.Save() MethodSqlTransaction.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.

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.

Page 49: ADO1

SqlCommand SqlCommand

Page 50: ADO1

SqlCommandSqlCommand

• 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

• 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

Page 51: ADO1

SQLCommand ClassSQLCommand 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

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

Page 52: ADO1

public SqlCommand();

public SqlCommand(string);

public SqlCommand(string, SqlConnection);

public SqlCommand(string, SqlConnection, SqlTransaction);

 

public SqlCommand();

public SqlCommand(string);

public SqlCommand(string, SqlConnection);

public SqlCommand(string, SqlConnection, SqlTransaction);

 

SQLCommand constructorsSQLCommand constructors

Page 53: ADO1

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;

}

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 ExampleSQLCommand Example

Page 54: ADO1

SQLCommand PropertiesSQLCommand Properties

ConnectionConnection Gets or sets the SqlConnection used by this instance of the SqlCommand.Gets or sets the SqlConnection used by this instance of the SqlCommand.

CommandTimeoutCommandTimeout Gets or sets the wait time before terminating the attempt to execute a command and generating an error.

Gets or sets the wait time before terminating the attempt to execute a command and generating an error.

CommandTextCommandText Gets or sets the Transact-SQL statement or stored procedure to execute at the source.Gets or sets the Transact-SQL statement or stored procedure to execute at the source.

CommandTypeCommandType Gets or sets a value indicating how the CommandText property is to be interpreted.Gets or sets a value indicating how the CommandText property is to be interpreted.

TransactionTransaction Gets or sets the transaction in which the SqlCommand executesGets or sets the transaction in which the SqlCommand executes

ParametersParameters Gets the SqlParameterCollection.Gets the SqlParameterCollection.

Page 55: ADO1

SQLCommand ExampleSQLCommand 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

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

Page 56: ADO1

SqlCommand MethodsSqlCommand Methods

ExecuteNonQueryExecuteNonQuery Executes a Transact-SQL statement against the Connection and returns the number of rows affected.Executes a Transact-SQL statement against the Connection and returns the number of rows affected.

ExecuteReaderExecuteReader Overloaded. Sends the CommandText to the Connection and builds a SqlDataReader.Overloaded. Sends the CommandText to the Connection and builds a SqlDataReader.

ExecuteScalarExecuteScalar Executes the query, and returns the first column of the first row in the resultset returned by the query. Executes the query, and returns the first column of the first row in the resultset returned by the query.

ExecuteXmlReaderExecuteXmlReader Sends the CommandText to the Connection and builds an XmlReader object.Sends the CommandText to the Connection and builds an XmlReader object.

CancelCancel Cancels the execution of a SqlCommand.Cancels the execution of a SqlCommand.

CreateParameterCreateParameter Creates a new instance of a SqlParameter object.Creates a new instance of a SqlParameter object.

PreparePrepare Creates a prepared version of the command.Creates a prepared version of the command.

ResetCommandTimeoutResetCommandTimeout Resets the CommandTimeout property default.Resets the CommandTimeout property default.

Page 57: ADO1

SqlCommand.ExecuteNonQuery()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.

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.

Page 58: ADO1

SqlCommand.ExecuteReader()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.

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.

Page 59: ADO1

CommandBehaviour EnumCommandBehaviour Enum

CloseConnectionCloseConnection When the command is executed, the associated Connection object is closed when the associated DataReader object is closed.

When the command is executed, the associated Connection object is closed when the associated DataReader object is closed.

SchemaOnlySchemaOnly The query returns column information only and does not affect the database state.The query returns column information only and does not affect the database state.

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

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.

Page 60: ADO1

SqlCommand.ExecuteReader() Method

SqlCommand.ExecuteReader() Methodpublic void CreateSqlDataReaderDemo(string strSelectQuery,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();}

public void CreateSqlDataReaderDemo(string strSelectQuery,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();}

Page 61: ADO1

SqlCommand.ExecuteScalar() Method

SqlCommand.ExecuteScalar() Method Executes the query, 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 count(*) as NumberOfRegions from region";

Int count = (int) objCmd1.ExecuteScalar();

Executes the query, 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 count(*) as NumberOfRegions from region";

Int count = (int) objCmd1.ExecuteScalar();

Page 62: ADO1

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

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

Page 63: ADO1

SqlCommand.MethodsSqlCommand.MethodsSqlCommand.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.

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.

Page 64: ADO1

SqlParameterSqlParameter

Page 65: ADO1

SqlParameter ClassSqlParameter Class

Represents a parameter to a SqlCommand, and optionally, its mapping to DataSet columns.

This class cannot be inherited.

Parameter names are not case sensitive.

Represents a parameter to a SqlCommand, and optionally, its mapping to DataSet columns.

This class cannot be inherited.

Parameter names are not case sensitive.

Page 66: ADO1

SqlParameter.ParameterName Property

SqlParameter.ParameterName Property

Gets or sets the name of the SqlParameter

The ParameterName is specified in the form @paramname.

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

Gets or sets the name of the SqlParameter

The ParameterName is specified in the form @paramname.

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

Page 67: ADO1

SqlParameter.DbType & SqlDbType Property

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

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

Page 68: ADO1

SqlParameter.Direction PropertySqlParameter.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

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

InputInput The parameter is an input parameter.The parameter is an input parameter.

InputOutputInputOutput The parameter is capable of both input and output.The parameter is capable of both input and output.

OutputOutput The parameter is an output parameter.The parameter is an output parameter.

ReturnValueReturnValue The parameter represents a return value from an operation such as a stored procedure, built-in function, or user-defined function.

The parameter represents a return value from an operation such as a stored procedure, built-in function, or user-defined function.

Page 69: ADO1

SqlParameter.Size PropertySqlParameter.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 does not include the terminating character.

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 does not include the terminating character.

Page 70: ADO1

SqlParameter.Precision & Scale Property

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

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

Page 71: ADO1

SqlParameters CollectionSqlParameters Collection

Page 72: ADO1

SqlParametersCollection ClassSqlParametersCollection Class

CountCount Gets the number of SqlParameter objects in the collection. Gets the number of SqlParameter objects in the collection.

ItemItem Overloaded, Gets the SqlParameter with a specified attribute. public SqlParameter this[int] {get; set;} --- Index public SqlParameter this[string] {get; set;}---parameter name

Overloaded, Gets the SqlParameter with a specified attribute. public SqlParameter this[int] {get; set;} --- Index public SqlParameter this[string] {get; set;}---parameter name

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

Page 73: ADO1

SqlParametersCollection MethodsSqlParametersCollection Methods

MethodMethod DescriptionDescription

AddAdd Overloaded. Adds a SqlParameter to the SqlParameterCollection.Overloaded. Adds a SqlParameter to the SqlParameterCollection.

InsertInsert Inserts a SqlParameter in the collection at the specified index.Inserts a SqlParameter in the collection at the specified index.

RemoveRemove Removes the specified SqlParameter from the collection.Removes the specified SqlParameter from the collection.

RemoveAtRemoveAt Overloaded. Removes the specified SqlParameter from the collection.Overloaded. Removes the specified SqlParameter from the collection.

ClearClear Removes all items from the collection.Removes all items from the collection.

ContainsContains Overloaded. Indicates whether a SqlParameter exists in the collection.Overloaded. Indicates whether a SqlParameter exists in the collection.

IndexOfIndexOf Overloaded. Gets the location of a SqlParameter in the collection.Overloaded. Gets the location of a SqlParameter in the collection.

Page 74: ADO1

SqlParametersCollection.Add() Method

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;

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;

Page 75: ADO1

SqlParametersCollection.Insert() Method

SqlParametersCollection.Insert() Method

Inserts a SqlParameter in the collection at the specified index.

public void Insert( int index, object value);

Inserts a SqlParameter in the collection at the specified index.

public void Insert( int index, object value);

Page 76: ADO1

SqlParametersCollection.Remove() Method

SqlParametersCollection.Remove() Method

Removes the specified SqlParameter from the collection.

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.

Removes the specified SqlParameter from the collection.

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.

Page 77: ADO1

SqlParametersCollection.RemoveAt() SqlParametersCollection.RemoveAt()

Removes the specified SqlParameter from the collection.

public void RemoveAt(int); -- Parameter Index

public void RemoveAt(string); - Parameter Name

Removes the specified SqlParameter from the collection.

public void RemoveAt(int); -- Parameter Index

public void RemoveAt(string); - Parameter Name

Page 78: ADO1

SqlParametersCollection.CopyTo()SqlParametersCollection.CopyTo()

Copies SqlParameter objects from the 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);

Copies SqlParameter objects from the 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);

Page 79: ADO1

SqlParametersCollection.Clear() Method

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;

}

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;

}

Page 80: ADO1

SqlParametersCollection.Contains()SqlParametersCollection.Contains()

Indicates whether a SqlParameter exists in the collection.

OverLoads

public bool Contains(object);

public bool Contains(string);

Indicates whether a SqlParameter exists in the collection.

OverLoads

public bool Contains(object);

public bool Contains(string);

Page 81: ADO1

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

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

Page 82: ADO1

SqlDataReaderSqlDataReader

Page 83: ADO1

SqlDataReader SqlDataReader

• Forward-only data access

• “Lightweight” programming model– Less overhead than using SqlDataAdapter

• Instantiated & returned by SqlCommand.ExecuteReader

• Forward-only data access

• “Lightweight” programming model– Less overhead than using SqlDataAdapter

• Instantiated & returned by SqlCommand.ExecuteReader

Page 84: ADO1

SqlDataReaderClassSqlDataReaderClass Provides a means of reading a forward-only tablular-

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

Provides a means of reading a forward-only tablular-data-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.

Page 85: ADO1

SqlDataReaderClass PropertiesSqlDataReaderClass Properties

PropertyProperty DescriptionDescription

Field CountField Count Gets the number of columns in the current row.Gets the number of columns in the current row.

Is ClosedIs Closed Gets a value indicating whether the data reader is closed.Gets a value indicating whether the data reader is closed.

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

Records AffectedRecords Affected

Gets the number of rows changed, inserted, or deleted by execution of the Transact-SQL statement.Gets the number of rows changed, inserted, or deleted by execution of the Transact-SQL statement.

Page 86: ADO1

ADO.NET – SqlDataReaderClass.Close() MethodsADO.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();

// Close the connection when done with it. myConnection.Close();

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

// Close the connection when done with it. myConnection.Close();

Page 87: ADO1

SqlDataReader.IsDbNull() MethodSqlDataReader.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.

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.

Page 88: ADO1

SqlDataReader.Read() MethodSqlDataReader.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.

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.

Page 89: ADO1

SqlDataAdapterSqlDataAdapter

Page 90: ADO1

SqlDataAdapter Class SqlDataAdapter Class

• Bridge between the DataSet and the data store– Inherited from the DataAdapter class

• Means to modify the DataSet and data source

• Bridge between the DataSet and the data store– Inherited from the DataAdapter class

• Means to modify the DataSet and data source

data store DataSetDataAdapter

Page 91: ADO1

SqlDataAdapter classSqlDataAdapter 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

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

Page 92: ADO1

SqlDataAdapter ConstructorSqlDataAdapter Constructor

public SqlDataAdapter();

public SqlDataAdapter(SqlCommand);

public SqlDataAdapter(qrystring, SqlConnection);

Page 93: ADO1

SqlDataAdapter PropertiesSqlDataAdapter PropertiesPropertyProperty DescriptionDescription

SelectCommandSelectCommand Gets or sets a Transact-SQL statement used to select records in the data source.Gets or sets a Transact-SQL statement used to select records in the data source.

InsertCommandInsertCommand Gets or sets a Transact-SQL statement to insert new records into the data source.Gets or sets a Transact-SQL statement to insert new records into the data source.

DeleteCommandDeleteCommand Gets or sets a Transact-SQL statement to delete records from the data set.Gets or sets a Transact-SQL statement to delete records from the data set.

UpdateCommandUpdateCommand Gets or sets a Transact-SQL statement used to update records in the data source.

Gets or sets a Transact-SQL statement used to update records in the data source.

TableMappings (inherited from DataAdapter)TableMappings (inherited from DataAdapter)

Gets a collection that provides the master mapping between a source table and a DataTable.

Gets a collection that provides the master mapping between a source table and a DataTable.

Page 94: ADO1

SqlDataAdapter MethodsSqlDataAdapter Methods

Fill (inherited from DbDataAdapter)Fill (inherited from DbDataAdapter)

Adds or refreshes rows in the DataSet to match those in the data source.Adds or refreshes rows in the DataSet to match those in the data source.

Update (inherited from DbDataAdapter)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".

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

Page 95: ADO1

SqlDataAdapter.Update() MethodSqlDataAdapter.Update() Method

public int Update(DataRow[]);

public override int Update(DataSet);

public int Update(DataTable);

public int Update(DataRow[]);

public override int Update(DataSet);

public int Update(DataTable);

Page 96: ADO1

System.Data NamespaceSystem.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

• 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

Page 97: ADO1

Introducing the Objects…Introducing the Objects…

• 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

System.Data

DataTable

DataRow

DataRelation

DataColumn

DataViewManager

DataSet

Page 98: ADO1

DataSet Tables

DataTable

Putting the Objects Together…Putting the Objects Together…

Relations

DataRelation

DataRelation

DataRow(s)

DataColumn

Constraint(s)

DataTable

DataTable

DataView

DataViewManager

Page 99: ADO1

Working Data - The DataSetWorking 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

• 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

Page 100: ADO1

Properties & Methods of InterestProperties & 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

Page 101: ADO1

All About Data!

Universal Data Container

DataSet: It’s not just for Databases

Page 102: ADO1

The DataTableThe 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 table’s

ConstraintsCollection– DataSet: Returns the DataSet of the DataTable – PrimaryKey: Gets the DataColumns that make up the

table’s primary key

Page 103: ADO1

DataSet and DataTableDataSet 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 DataColumnDataColumn 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 DataSetds.Tables.Add( dt );

Page 104: ADO1

Relating Data - The DataRelationRelating 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 DataSet’s Relations property

• 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 DataSet’s Relations property

Page 105: ADO1

Creating Relations With DataRelations

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

Page 106: ADO1

XML and the DataSetXML 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

Page 107: ADO1

Methods of Reading and Writing XMLMethods 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 DataSet’s XMLSchema to an XML Documentmds.WriteXmlSchema( oFile );

// Read/Upload XML Data into the DataSetmds.ReadXml( iFile);

// modify the data // ...

// Write the existing Data to an XML Documentmds.WriteXml( "C:\\My_ADO.NET\\myXmlData.txt", XmlWriteMode.DiffGram);

Page 108: ADO1

Viewing Data - The DataViewViewing 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 table’s sort columns and sort order

• 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 table’s sort columns and sort order

Page 109: ADO1

Creating a DataView Creating a DataView // Code for myTable “Customers” with “Name” column not shownDataView 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”);

//...

Page 110: ADO1

SummarySummary• 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

• 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