ADO.NET Participant Manual

115
ADO.NET Participant Manual

Transcript of ADO.NET Participant Manual

ADO.NET

Participant Manual

ADO.Net

1 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Notes

…………………………………………………………………………………………………………………………

….………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

2 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………….

Introduction to ADO.Net

ADO.NET is an object-oriented set of libraries that allows you to interact with data sources. Commonly,

the data source is a database, but it could also be a text file, an Excel spreadsheet, or an XML file. For

the purposes of this training, we will look at ADO.NET as a way to interact with a data base.

As you are probably aware, there are many different types of databases available. For example Microsoft

SQL Server, Microsoft Access, Oracle and IBM DB2, just to name a few.

If you are already familiar with relational databases such as Microsoft SQL Server, you will encounter

many familiar terms in ADO.NET. Tables, rows, columns, relations, views; these ADO.NET concepts are

based loosely on their relational database counterparts. Despite these similarities, ADO.NET is not a

relational database because it doesn’t include key “relational algebra” features typically found in robust

database systems. It also lacks many of the common support features of such databases, including

indexes, stored procedures, and triggers.Still, if you limit yourself to basic create, read, update, and delete

(CRUD) operations, ADO.NET can act like a miniature yet powerful in-memory database.

Why ADO.Net?

In the early days of computer programming, the need for a data library like ADO.NET didn’t exist.

Programmers had only a single method of accessing data: direct interaction with the values in memory.

Permanently stored data existed on tape reels in fire-resistant, climate controlled, and raised-floor rooms.

Data queries could take hours, especially if someone with more clout had a higher-priority processing

need.

Over time, computers increased in complexity, and (as if to fill some eternal maxim) data processing

needs also expanded to consume all available computing resources. Businesses sought easier ways to

manage entire records of numeric, text, and date-time values on their mainframe systems. Flat-file and

relational database systems sprang up to establish proprietary management of millions of data values. As

personal computers arrived and matured, developers soon had several database systems at their

disposal.

Major Components of ADO.NET

Each table defines DataColumnitems, each representing the individual data values that appear in the

table’s records. DataColumndefinitions include a data type declaration based on the kind of data

destined for each column. For instance, a CustomerLastNamecolumn might be defined to use data of

type System.String, whereas an OrderSalesTaxcolumn could be crafted for use with

System.Decimalcontent.

ADO.Net

3 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

One DataRowentry exists for each record of data stored within a table, providing access to the

distinct columnar data values. ADO.NET includes methods that let you add to, delete from, modify,

and query each DataTableobject’s rows. For tables connected to an external data storage area, any

changes made can be propagated back to the source.

You can optionally establish links between the tables of data using DataRelationentries.

Programmatic limitations can be placed on tables and their data values using Constraint instances.

DataViewinstances provide a limited or modified view of the rows in a DataTable.

Tables can be grouped together into a DataSet. Some tools that interact with ADO.NET data require

that any tables be bound within a DataSet, but if you plan to do some limited work with only a single

table, it’s fine to work with just the DataTableinstance.

Features

Disconnected Data Architecture

Data Cached in Datasets

Scalability

Data transfer in XML format

Extensions to ADO.NET

Generalizing access to data is a key benefit of using ADO.NET. But an even greater advantage for .NET

developers is that all values managed through ADO.NET appear as objects, first-class members of the

.NET data world. Each data field in a table is a strongly typed data member, fully compliant with .NET’s

Common Type System. Individual fields can be used just like any other local variable. Data rows and

other sets of objects are standard .NET collections and can be processed using standard iteration

methods.

Because ADO.NET values exist as true .NET objects and collections, Microsoft has enhanced the core

ADO.NET feature set with new tools. Two of these technologies, the Entity Framework and LINQ, are not

formally part of ADO.NET. But their capability to interact with and enhance the ADO.NET experience

makes them essential topics for study.

Connecting to External Data

Establishing External Connections, introduces the code elements that support communications between

ADO.NET and external sources of data. Although using only code to establish these connections is quite

common, Visual Studio also includes the Data Source Connection Wizard, a mouse-friendly tool that

guides you through the creation of a ready to- use DataSet. Here’s an example of using the Connection

Wizard.

ADO.Net

4 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

ADO.Net

5 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Notes

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………….…

ADO.Net

6 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………….……

ADO.Net

7 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Creating and Managing Connection

Whenever you are working in with the database connection environment you need to connect to a

database for retrieving the data and updating the database. Here we will show you how to connect to a

variety of data sources from ADO.NET; how to handle security-related issues including storing connection

strings and using different authentication methods; and how to set up, monitor, and optimize connection

pooling.

A .NET Framework data provider is used to connect to a data source, execute commands, and retrieve

results. The .NET Framework ships with the data providers shown in below table.

Data providers included in the .NET Framework

.NET Framework data provider Data source access

SQL Server Microsoft SQL Server version 7.0 or later

OLE DB Data sources using OLE DB

ODBC Data sources using ODBC

Oracle Oracle client software version 8.1.7 or later

ADO.NET has both connected and disconnected classes. The connected classes let you retrieve and

update data in underlying data sources. The disconnected classes let you access and manipulate offline

the data you retrieved using the connected classes and later synchronize it with the underlying data

source using the connected class.

In order to perform these tasks, you need to perform the following steps:

1. Create a connection object.

2. Create a Command object

3. Open the Connection Object.

4. Execute Database Application statements in the command object.

5. Close the connection object.

ADO.Net

8 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Connections, Connection Strings, and Connection Pooling

Database connections are a critical and limited resource. Connections must be managed to ensure that

an application performs well and is scalable. SQL Server and Oracle data providers provide connection

pooling, while the OLE DB and ODBC providers use the pooling provided by OLE DB or ODBC,

respectively.

Connections should be opened as late as possible and closed as soon as possible using the

Close()method. Alternatively, you can create the connection in a using block to ensure that the system

disposes of the connection when the code exits the block. The connection should be used as briefly as

possible, meaning that connections should not last longer than a method call. Connections should not be

passed between methods—in addition to creating performance problems and limiting scalability, this can

lead to security vulnerabilities

Creating a Connection Object

If you are creating a database application, you will eventually need to open a connection to that database.

An ADO.NET Connection object allows you to create that connection. You will also need to retrieve and

modify data in the database, and that is where you will need to use the ADO.NET Command object.

Creating a SqlConnection Object

SqlConnection conn = new SqlConnection( "Data Source=(local); Initial Catalog=Northwind; Integrated

Security=SSPI");

ADO.NET Connection Strings contain certain key/value pairs for specifying how to make a database

connection. They include the location, name of the database, and security credentials

Connection String Parameter

Name Description

Data Source Identifies the server. Could be local machine, machine domain name,

or IP Address.

Initial Catalog Database name.

Integrated Security Set to SSPI to make connection with user's Windows login

User ID Name of user configured in SQL Server.

Password Password matching SQL Server User ID.

SqlConnection conn = new SqlConnection(

"Data Source=DatabaseServer; Initial Catalog=Northwind; User ID=YourUserID;

Password=YourPassword");

ADO.Net

9 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

As we've already seen how to instantiate a SqlConnection. The rest of the steps, opening, passing,

using, and closing are shown in this example.

using System;

using System.Data;

using System.Data.SqlClient;

/// <summary>

/// Demonstrates how to work with SqlConnection objects

/// </summary>

class SqlConnectionDemo

{

static void Main()

{

// 1. Instantiate the connection

SqlConnection conn = new SqlConnection(

"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");

SqlDataReaderrdr = null;

try

{

// 2. Open the connection

conn.Open();

// 3. Pass the connection to a command object

SqlCommandcmd = new SqlCommand("select * from Customers", conn);

//

// 4. Use the connection

//

// get query results

rdr = cmd.ExecuteReader();

// print the CustomerID of each record

while (rdr.Read())

{

Console.WriteLine(rdr[0]);

}

}

finally

{

ADO.Net

10 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

// close the reader

if (rdr != null)

{

rdr.Close();

}

// 5. Close the connection

if (conn != null)

{

conn.Close();

}

}

}

}

As shown in above example, you have opened a connection by calling the Open() method of the

SqlConnection instance, conn. Any operations on a connection that was not yet opened will generate an

exception. So, you must open the connection before using it.

Connection Strings

You next create a connection string that points to a SQL Server database. A connection string has a set

of semi-colon-separated attributes. Each .Net Data Provider connection string looks different; depending

on the type of .NET Data Provider you need to use and which attributes are set for each different type of

database system. For example, the connection string below is an example of what you use to connect to

a local SQL Server.

Data Source= (local); Initial Catalog=Northwind; User ID=sa; Password= YourUserID;

The connection string shown below is an example of how you would connect to a Microsoft Access 2000

database using the OleDbConnection object in System.Data.OleDb.

Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\Northwind.mdb

Creating a Command Object

Command object has the following important properties.

Connection: used to specify the connection to be used by the command object.

CommandType: Used to specify the type of SQL command you want to execute. To assign a value

to this property, use the enumeration CommandType that has the members Text, StoredProcedure

and TableDirect. Text is the default and is set when you want to execute ant SQL command with

ADO.Net

11 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

command object. StoredProcedure is set when you want to call a stored procedure or function and

TableDirect is set when you want to retrieve data from the table directly by specifying the table name

without writing a select statement.

CommandText: Used to specify the SQL statement you want to execute.

Transaction: Used to associate a transaction object to the command object so that the changes

made to the database with command object can be committed or rollback.

The following code snippet demonstrates how to create a command object:

//Create an object of the SqlConnection class

SqlConnection connection= new SqlConnection();

//Create a connection string to the HR database

connection.ConnectionString =”Data Source= SQLSERVER01; Initial Catalog=HR; User ID= sa;

Password=YourUserID”;

//Create an object of the SqlCommand class

SqlCommandcmd=new SqlCommand(“select * from monthlysalary”, connection);

Opening the Connection Object.

The following code snippet demonstrates how to establish an open connection:

//Create an object of the SqlConnection class

Sqlconnection connection = new SqlConnection();

//Create a connection string to the HR databases

connection.ConnectionString =”Data Source =SQLSERVER01; Initial Catalog=HR; User ID= sa;

Password= YourUserID”;

//Open the connection

connection.open();

//Create an object of the SqlCommand class

SqlCommand cmd=new SqlCommand(“select * from monthlysalary”, connection);

Executing SQL Statements in the Command Object

Objects exposes methods for executing commands based on the type of command and desired return

value, as described in the following table.

Command Return Value

ADO.Net

12 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

ExecuteReader Returns a DataReader object.

ExecuteScalar Returns a single scalar value.

ExecuteNonQuery Executes a command that does not return any rows.

ExecuteXMLReader Returns an XmlReader. Available for a SqlCommand object only.

Each strongly typed command object also supports a CommandType enumeration that specifies how a

command string is interpreted, as described in the following table.

CommandType Description

Text An SQL command defining the statements to be executed at the data source.

StoredProcedure

The name of the stored procedure. You can use the Parameters property of a

command to access input and output parameters and return values, regardless of

which Execute method is called. When using ExecuteReader, return values and

output parameters will not be accessible until the DataReader is closed.

TableDirect The name of a table.

The following code snippet demonstrates how to execute SQL statements in a command object:

//Create an object of the SqlConnection class

Sqlconnection connection = new SqlConnection();

//Create a connection string to the HR database

Connection.ConnectionString =”Data Source =SQLSERVER01; Initial Catalog=HR; User ID= sa;

Password= YourUserID”;

//Open the connection

Connection.open();

//Create an object of the SqlCommand class

SqlCommand cmd=new SqlCommand(“select * from monthlysalary”, connection);

//Create an object of the SqlDataReader class

SqlDataReader myReader = cmd.ExecuteReader();

Closing the Connection object

The following code snippet demonstrates how to close an open connection:

//Create an object of the SqlConnection class

ADO.Net

13 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Sqlconnection connection = new SqlConnection();

//Create a connection string to the HR database

Connection.ConnectionString =”Data Source =SQLSERVER01; Initial Catalog=HR; User ID= sa;

Password= YourUserID”;

//Open the connection

Connection.open();

//Create an object of the SqlCommand class

SqlCommand cmd=new SqlCommand(“select * from monthlysalary”, connection);

//Create an object of the SqlDataReader class

SqlDataReader myReader = cmd.ExecuteReader();

//Read a row of data at a time

myReader.Read();

//Close a connection

Connection.close();

Handling Connection Events

All of the .NET Framework data providers have Connection objects with two events that you can use to

retrieve informational messages from a data source or to determine if the state of a Connection has

changed.

The connection objects have events associated with it that are to retrieve information namespaces from a

data source or to determine if the state of a connection object has changed.

The connectionState enumeration of the System.Data namespace describes the current state of the

connection to a data source. The various members of the ConnectionState are discussed in the following

table

Member

Name Description

Broken In this case the connection the data source is broken. This can occur only after the

connection has been opened.

Closed In this case the connection to the data source is closed.

Connecting Ion this case connection object is connecting to the data source.

Executing In this case the connection object executes a command.

Fetching In this case the connection object retrieves the data.

Open In this case the connection to the data source is opened.

ADO.Net

14 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

The following table describes the events of the Connection object.

Event Description

InfoMessage

Occurs when an informational message is returned from a data source. Informational

messages are messages from a data source that do not result in an exception being

thrown.

StateChange Occurs when the state of the Connection changes.

Working with the InfoMessage Event

The InfoMessage event receives anSqlInfoMessageEventArgs object containing, in its Errors property, a

collection of the messages from the data source. You can query the Error objects in this collection for the

error number and message text, as well as the source of the error. The .NET Framework Data Provider

for SQL Server also includes detail about the database, stored procedure, and line number that the

message came from. Following are the properties of the SqlInfoMessageEventArgs:

Errors: It is used to get the collection of warnings sent from the server.

Message: It is used to get the full text of the error sent from the database.

Source: It is used to get the name of the object that generated the error.

Example :

// Assumes that connection represents a SqlConnection object.

connection.InfoMessage += new SqlInfoMessageEventHandler(OnInfoMessage);

protected static void OnInfoMessage( object sender, SqlInfoMessageEventArgs args)

{

foreach (SqlError err in args.Errors)

{

Console.WriteLine( "The {0} has received a severity {1}, state {2} error number {3}\n"

+ "on line {4} of procedure {5} on server {6}:\n{7}",err.Source, err.Class, err.State, err.Number,

err.LineNumber, err.Procedure, err.Server, err.Message);

}

}

Working with the StateChange Event

ADO.Net

15 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

CurrentState is a ConnectionState enumeration that indicates the state of the Connection after it

changed.

The Following are the properties of StateChangerEventArgs.

CurrentState: It is used to get new state of the connection.

OrigininalState: It is used to get the original state of the connection.

The following code example uses the StateChange event to write a message to the console:

// Assumes connection represents a SqlConnection object.

connection.StateChange += new StateChangeEventHandler(OnStateChange);

protected static void OnStateChange(object sender, StateChangeEventArgs args)

{

Console.WriteLine("The current Connection state has changed from {0} to {1}.",args.OriginalState,

args.CurrentState);

}

Implementing Connection Pooling

Establishing connection to a database is cumbersome and resource burning, most important job in the

applications, sometimes it might be slow. Most of the applications need to execute any query on the

database server, a connection need to be established. Knowing about the Connection Pooling concepts

and tips will definitely improves the performance while connecting to the database and the same time

solves the requirement.

Connection pooling is controlled by certain parameters that are placed into the connection string. These

parameters are described in the following table.

Parameter Description

Connection timeout It is time in seconds to wait while a connection to the data source is

attempted. The default value is 15 seconds.

Min pool size It is use to mention the minimum number of connections maintained in the

pool. The default value is 0.

Max pool size It is used to mention the maximum number od connections allowed on the

pool. The default value is 100.

Pooling When true, it couses the request for a new connection to be drawn from

the pool.

When an application attempts to open a connection, the pooler examines the security context and the

pooling property of the connection string and takes one of the following actions

ADO.Net

16 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

If the pooling property is false, the pooler opens a new connection rather than attempting to accure a

connection from a pool.

If the pooling property is true, which is the default setting, the pooler attempts to acquire a connection

from a pool.

You need to remember these all the points at time of connection pooling

Disabling the connection pooling, infers that the connection object that is created by the user will not

be re-used to any other user.

A Connection pool will be created when Open() method of connection object is called. If the same

application is using multiple Connection Strings (say more than one) then multiple connection pools

will be created corresponding to each connection string.

Connection Pooling is applied in ADO.Net by default.

Connections that are not explicitly closed are not added or returned to the pool. Hence The Close() or

Dispose() method of Connection need to be called to close the connection.

A Connection Pool is freed from the memory when the last connection to the database is closed.

Connection Pool’s life time is ended as soon as the application domain is unloaded. For example at

any time when IISRESET runs the Connection Pool gets destroyed

Connection Pools cannot be shared across application domains.

The following code snippet illustrates an example of connection pooling:

SqlConnection connection = new SqlConnection( );

connection.StateChange += new StateChangeEventHandler(connection_StateChange);

connection.ConnectionString = sqlConnectString + "Connection Timeout=15;Connection Lifetime=0;" +

"Min Pool Size=0;Max Pool Size=100;Pooling=true;";

connection.Open();

connection.Close();

connection.ConnectionString = sqlConnectString +

"Connection Timeout=30;Connection Lifetime=0;" +

"Min Pool Size=0;Max Pool Size=200;Pooling=true;";

connection.Open();

connection.Close();

ADO.Net

17 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Querying Data

When using a SQL select command, you retrieve a data set for viewing. To accomplish this with a

SqlCommand object, you would use the ExecuteReader method, which returns a SqlDataReader object.

We'll discuss the SqlDataReader in a future lesson. The example below shows how to use the

SqlCommand object to obtain a SqlDataReader object:

// 1. Instantiate a new command with a query and connection

SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);

// 2. Call Execute reader to get query results

SqlDataReader rdr = cmd.ExecuteReader();

Inserting Data

To insert data into a database, use the ExecuteNonQuery method of the SqlCommand object. The

following code shows how to insert data into a database table:

// prepare command string

string insertString = @"

insert into Categories

(CategoryName, Description)

values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')";

// 1. Instantiate a new command with a query and connection

SqlCommand cmd = new SqlCommand(insertString, conn);

// 2. Call ExecuteNonQuery to send command

cmd.ExecuteNonQuery();

Activity: Creating and Managing Connection

1. Write a Program to make a connection with SQL Server table Name Employee Records.

ADO.Net

18 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

2. Write a program where you have to develop an application that will display the

employeedetails for the given situation.

Marvin & Company is a leading producer and distributer of chips in the United State and they

are planning to start its annual appraisal process. Before starting up with the appraisal

process, the senior management requires a list of all employees. The details include employee

name, employee code, current position, designation and joining date.

ADO.Net

19 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Notes

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

20 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

21 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Introducing Data Binding

Data binding provides a way for developers to create a read/write link between the controls on a form and

the data in their application (their data model). Classically, data binding was used within applications to

take advantage of data stored in databases. Windows Forms data binding allows you to access data

from databases as well as data in other structures, such as arrays and collections.

Basic Data Binding Concepts

Regardless of what element you are binding and the nature of your data source, each binding always

follows the model illustrated by the following figure:

Direction of the Data Flow

As mentioned previously and as indicated by the arrow in the figure above, the data flow of a binding can

go from the binding target to the binding source (for example, the source value changes when a user

edits the value of a TextBox) and/or from the binding source to the binding target (for example, your

TextBox content gets updated with changes in the binding source) if the binding source provides the

proper notifications.

ADO.Net

22 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

ADO.Net

23 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Simple Data Binding

Simple binding allows us to display one data element from a table in a control. Simple binding is managed

by use of the Bindings collection on each control. Simple bound controls show only one data element at a

time. We have to create our own navigation controls (buttons) to see other data elements. These

navigation controls allow us to move from record to record by clicking buttons and the data in the bound

controls will be updated automatically. To bind any property of a control, you need to click the ellipse

button of the Advanced property under Data Bindings property in the properties window. Clicking on the

ellipse opens up Advanced Data Binding Dialog in which we can bind any property of a control to a data

source.

Complex Data Binding

Complex data binding is the ability of a control to bind to more than one data element, typically more than

one record in a database, or to more than one of any other type of bindable data elements. Examples of

controls that support complex binding are the DataGridView, ListBox, and ErrorProvider controls.

Control Name Description

ListBox

This control is used for a column from multiple records of a dataset. The DataSource property of the ListBox control is used to bind the control to a data source, such as a DataSet or DataTable. The DisplayMember property of the ListBox control is used to bind the control to a specific data element, such as column of a DataTable.

ComboBox

This control has two parts, a text box for entering data and a drop-down list for displaying the data. The DataSource property of the ComboBox control is used to bind the control to a DaraSource, such as DataSet or DataTable. The DisplayMember property of the ComboBox control is used to bind the control to a specific data element, such as a column of a DataTable.

DataGrid/View This control can display from multiple records as well as multiple columns. The DataSource property of the DataGridView control is used to bind the element to a specific data element. Such as a column of DaraTable.

Binding to a ComboBox or ListBox

In this section let us create a complex binding by using a ComboBox and a ListBox. As in the preceding

section the user must add a database connection to the project and to generate DataSets. Then he must

proceed to create a new Windows Application Project by name ComplexDataBindingDemo. After creating

ADO.Net

24 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

the Data Connection to the SQLServer Database, from the ToolBox, he must drag and drop a DataGrid

control and a list box

We need to create the following objects:

A class implementing ITypedList and IBindingList (your collection)

A class that is your data (lots of properties and stuff)

A class implementing IComparer (for sorting)

A class implementing PropertyDescriptor (for using non grig compatable types, like SqlTypes )

A class implementing Attribute (so we know whats in the collection)

Navigation between records

For every data source that is bound to a Windows form control, there exists a BindingNavigation control.

The BindingNavigation control handles the binding to the data source by keeping a pointer to the

current item in the record list.

The following figure illustrates the relationship between the BindingNavigator control and a Windows

form.

s

The following figure displays the BindingNavigator control and the BindingSource control displayed in a

Windows form.

Windows Form

Control 1

Control 2

Control 3

BindingNavigator 1

BindingNavigator 3

BindingNavigator 2

DATASOURCE 1

DATASOURCE 3

DATASOURCE 2

ADO.Net

25 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

As shown in the preceding figure, BindingNavigator control has various controls for modifying the data

source. The following table describes the various controls, their symbols and function in the

BindingNavigator control.

ADO.Net

26 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Control Symbol Function

BindingNavigatorAddItembutton

Inserts a new row the data source.

BindingNavigatorDeleteItem button

Deletes the current row from the data source

BindingNavigatorMoveFirstItem

button Moves to the first item in the data cource.

BindingNavigatorMoveLastItem

button Moves to the last item in the data source.

BindingNavigatorMoveNextItem

button Moves to the next item in the data source.

BindingNavigatorMovePreviousItem

button

Moves to the previous item in the data

source.

BindingNavigatorPositionItem text

box

Return the current position within the data

source.

BindingNavigatorCountItem text

box

Return the total number of item in the data

source.

Activity: Introducing Data Binding

1. Write a program where you need to create a Window form to show the monthly Salary details

of an employee. The details need to be displayed in the following customized format.

ADO.Net

27 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

2. Continue with the Previous Chapter Activity (Marvin & Company), you need to retrieve the

department details for Mr. Smith Carol who is the Vice President of the company; he wants to

view all the details of various departments functioning in the organization in a customized

format, you need to create a format of the form and help Mr. Virendra to complete his

requirement. The details need to be displayed in the following customized format.

3. Continue with the Previous Activity (Marvin & Company), again you need to retrieve the

department details for Mr. Smith Carol for various departments functioning in the

organization in a customized format, but here you need to create a format of the form with

ADO.Net

28 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Grid Tools and help Mr. Virendra to complete his requirement. The details need to be

displayed in the following customized format.

ADO.Net

29 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Notes

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

30 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

31 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

32 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Filtering Data

What is Query?

A database query is a piece of code (a query) that is sent to a database in order to get information back

from the database. It is used as the way of retrieving the information from database.

A database "query" is basically a "question" that you ask the database. The result of the query is the

information that is returned by the database management system. Queries are usually constructed using

SQL (structured query language) which resembles a high-level programming language.

Purpose of a Query

ADO.NET supports many ways to manage memory-resident data returned in a DataSet. Here you will

see that ADO.NET exposes additional functionality to the ways you can sort and filter data. Because of

the very nature of the disconnected DataSet architecture used in ADO.NET, it's often impractical or

impossible to requery a remote data source to reorder or further filter data. Of course, this assumes that

you are not implementing a traditional client/server application, which can execute further server-side

sorting and filtering.

Filtering and Sorting with the DataTable Select Method

The DataTable Select returns a DataRow array from a table per a particular filter and/or sort order. The

content reflects changes to the underlying table, but the membership and ordering remain static.

The DataTable Select method accepts a filter and sort argument to return an arry of DataRow objects that

conform to the criteria in a FilterExpression.

public DataRow[] Select(); Gets an array of all DataRow objects.

public DataRow[] Select(string); Gets an array of all DataRow objects that

match the filter criteria

public DataRow[] Select(

string, string);

Gets an array of all DataRow objects that

match the filter criteria, in the specified sort

order

public DataRow[] Select(

string, string, DataViewRowState);

Gets an array of all DataRow objects that

match the filter in the order of the sort, that

match the specified state

Filtering and Sorting with the DataView Object

A DataView enables you to create different views of the data stored in a DataTable, a capability that is

often used in data-binding applications. Using a DataView, you can expose the data in a table with

different sort orders, and you can filter the data by row state or based on a filter expression.

ADO.Net

33 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Sorting the DataView

To sort a DataView, construct a sort expression string, note that the Sort property can accept any number

of columns on which to sort the Rows collection. For example use the the following sort expression string:

"Price DESC, Title ASC"

Example

The following example illustrates how to filter and sort using the DataTable's DataView object.

ADO.Net

34 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Filtering and Sorting with the DataViewManager

If the DataSet contains multiple tables, an alternative is to create a DataViewManager object, which

works something like a DataSet global DataView. This new objects provides a single object that

manages a collection of DataView objects, each of which is associated with a specific DataTable in the

selected DataSet object. You can define individual DataView objects that sort or filter the data in each

DataTable; as a matter of fact, ADO.NET creates one for you as it creates each DataTable - all of which

can be managed by the DataViewManager.

You can use a DataViewManager to manage view settings for all the tables in a DataSet. If you have a

control that you want to bind to multiple tables, such as a grid that navigates relationships, a

DataViewManager is ideal.

ADO.Net

35 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Creating Parameterized queries

For developers, stored procedures have always been the method of data access from a database. This is

because stored procedures provide the benefits of precompiled execution, reduced network traffic, and

efficient reuse of code and enhanced security measures for the data stores in a database.

However, a more secure way is to create parameterized queries. By using parameterized queries, data

can be filtered based on the criterion entered by a user at run time. Parameterized queries can be used in

any situation where you need database operation to be executed on the SQL Server.

Consider the following SQL Query, where customers having a specific CustomerID are selected

Selected FirstName

From Customers

Where CustomerID=@CustomerID

Filtering Data Using Controls if a Windows Form

You can expose the sorting and filtering capability of BindingSource control through the Sort and Filter

properties. You can apply simple sorting when the underlying data source is an IBindingList, and you can

apply filtering and advanced sorting when the data source is an IBindingListView. The Sort property

requires standard ADO.NET syntax: a string representing the name of a column of data in the data

source followed by ASC or DESC to indicate whether the list should be sorted in ascending or

descending order. You can set advanced sorting or multiple-column sorting by separating each column

with a comma separator. The Filter property takes a string expression

ADO.Net

36 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Activity: Filtering Data

1. Write a program to solve the problem of Mr. John, the HR Manager of Marvin & Company, he

wants to view the Department Code, Department Name, Department Head and the Location.

You need to design an application that will display the required details as per entered

Location Name (Filter the Record Based on Location).

ADO.Net

37 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Notes

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

38 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

39 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

40 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Connected Environment

A connection object establishes the connection for the application with the database. The commandobject

provides direct execution of the command to the database. If the command returns more than asingle

value, the command object returns a DataReader to provide the data. Alternatively, theDataAdapter can

be used to fill the Dataset object. The database can be updated using the command object or the

DataAdapter.

A challenge related to data-centric application is that multiple users to access data simultaneously from

the data source. As the number of users accessing an application increases, the network becomes slow

and might lead to network congestion or hamper the application performance. Therefore, some of the

factors that decide the type the type of data access environment used for an application include number

of users who intend to use the application and the functionality of the application.

Connected Architecture of ADO.NET

The architecture of ADO.net, in which connection must be opened to access the data retrieved from

database is called as connected architecture. Connected architecture was built on the classes

connection, command, datareader and transaction.

In Connection Oriented Data Access Architecture the application makes a connection to the Data Source

and then interact with it through SQL requests using the same connection. In these cases the application

stays connected to the database system even when it is not using any Database Operations.

ADO.Net

41 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

ADO.Net

42 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

The Connection Object

The Connection object creates the connection to the database. Microsoft Visual Studio .NET provides two

types of Connection classes: the SqlConnection object, which is designed specifically to connect to

Microsoft SQL Server 7.0 or later, and the OleDbConnection object, which can provide connections to a

wide range of database types like Microsoft Access and Oracle. The Connection object contains all of the

information required to open a connection to the database. in connected architecture, the purpose of

connection is to just establish aconnection to database and it self will not transfer any data.

If you are using data design tools in Visual Studio, you often do not need to explicitly create a connection

object for your form or component. However, in some instances you might find it convenient to create a

connection alone.

Your options for creating a connection are:

Use any of the following data design tools, which create a connection object as part of the task they

are performing:

o Data Adapter Configuration Wizard - this wizard prompts you for information to create a

connection that is in turn linked to a data adapter. For more information, see Data Adapter

Configuration Wizard.

o Data Form Wizard - this wizard creates the connection object as part of the form it is

configuring. For more information, see Data Form Wizard.

Drag a table, selection of columns, or stored procedure from Server Explorer onto a form or

component. By dragging one of these elements onto a form, you create both a data adapter and a

connection. For more information, see Adding New Data Connections in Server Explorer.

Create a standalone connection. This option creates a connection object on your form or component

whose properties you configure manually. This strategy is useful if you intend to set connection

properties at run time or if you simply prefer setting the properties in the Properties window. The

procedure is described below.

Create a connection programmatically. For more information about creating and managing

connections in code, see Connecting to SQL Server Using ADO.NET and Connecting to an OLE DB

Data Source Using ADO.NET.

To create a connection

1. From the Data tab of the Toolbox, drag a connection object onto your form or component. For more

information about which connection object to use, see Introduction to ADO.NET Connection Design

Tools.

2. Select the connection in the designer and then use the Properties window to set its connection

string.

ADO.Net

43 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

o You can set the ConnectionString property as a single unit. (You cannot specify a Provider

attribute for a SqlConnection object.)

– or –

o You can set individual properties (DataSource, Database, UserName, and so on). If you set

individual properties, the connection string is built for you.

3. If you want to rename the connection object, set its Name property.

4. If you want to set properties at run time without recompiling the application, specify connection

properties. For more information about making connection properties dynamic, see Introduction to

ADO.NET Connection Design Tools. For an overview of dynamic properties, see Configuring

Applications Using Dynamic Properties.

The Command Object

The Command Object in ADO.NET executes SQL statements and Stored Procedures against the data

source specified in the Connection Object. The Command Object required an instance of a Connection

Object for executing the SQL statements. That is, for retrieving data or execute an SQL statement against

a Data Source , you have to create a Connection Object and open a connection to the Data Source, and

assign the open connection to the connection property of the Command Object. When the Command

Object return result set , a Data Reader is used to retrieve the result set.

Note: Storing connection-string details (such as the server name, user name, and password)

can have implications for the security of your application. Using Windows Integrated Security is a more

secure way to control access to a database.

Note: If connection information needs to be set at run time, you can configure connection

properties as dynamic properties.

Command

Connection

Data Source

ADO.Net

44 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

The Command Object has a property called CommandText, which contains a String value that represents

the command that will be executed in the Data Source. When the CommandType property is set to

StoredProcedure, the CommandText property should be set to the name of the stored procedure.

The Command object is represented by two corresponding classes: SqlCommand and OleDbCommand.

Command objects are used to execute commands to a database across a data connection. The Command

objects can be used to execute stored procedures on the database, SQL commands, or return complete

tables directly. Command objects provide three methods that are used to execute commands on the

database:

ExecuteNonQuery Executes commands that have no return values such as INSERT, UPDATE or

DELETE

ExecuteScalar Returns a single value from a database query

ExecuteReader Returns a result set by way of a DataReader object

After establishing a connection to a data source, you can execute commands and return results from the

data source using a DbCommand object. You can create a command using one of the command

constructors for the .NET Framework data provider you are working with. Constructors can take optional

arguments, such as an SQL statement to execute at the data source, a DbConnection object, or a

DbTransaction object. You can also configure those objects as properties of the command. You can also

create a command for a particular connection using the CreateCommand method of a DbConnection

object. The SQL statement being executed by the command can be configured using the CommandText

property.

Executing a Command

Each .NET Framework data provider included with the .NET Framework has a Command object. The

.NET Framework Data Provider for OLE DB includes an OleDbCommand object, the .NET Framework

Data Provider for SQL Server includes a SqlCommand object, the .NET Framework Data Provider for

ODBC includes an OdbcCommand object, and the .NET Framework Data Provider for Oracle includes an

OracleCommand object.

.NET Framework has its own command object that inherits from DbCommand. The .NET Framework

Data Provider for OLE DB includes an OleDbCommand object, the .NET Framework Data Provider for

SQL Server includes a SqlCommand object, the .NET Framework Data Provider for ODBC includes an

OdbcCommand object, and the .NET Framework Data Provider for Oracle includes an OracleCommand

ADO.Net

45 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

object. Each of these objects exposes methods for executing commands based on the type of command

and desired return value, as described in the following table.

Command Return Value

ExecuteReader Returns a DataReader object.

ExecuteScalar Returns a single scalar value.

ExecuteNonQuery Executes a command that does not return any rows.

ExecuteXMLReader Returns an XmlReader. Available for a SqlCommand object only.

Each strongly typed command object also supports a CommandType enumeration that specifies how a command string is interpreted, as described in the following table.

CommandType Description

Text An SQL command defining the statements to be executed at the data source.

StoredProcedure The name of the stored procedure. You can use the Parameters property of a

command to access input and output parameters and return values, regardless of

which Execute method is called. When using ExecuteReader, return values and

output parameters will not be accessible until the DataReader is closed.

TableDirect The name of a table.

Example:

The following code example demonstrates how to create a SqlCommand object to execute a stored

procedure by setting its properties. A SqlParameter object is used to specify the input parameter to the

stored procedure. The command is executed using the ExecuteReader method, and the output from the

SqlDataReader is displayed in the console window.

static void GetSalesByCategory(string connectionString, string categoryName)

{

using (SqlConnection connection = new SqlConnection(connectionString))

{

// Create the command and set its properties.

SqlCommand command = new SqlCommand();

command.Connection = connection;

command.CommandText = "SalesByCategory";

command.CommandType = CommandType.StoredProcedure;

// Add the input parameter and set its properties.

ADO.Net

46 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

SqlParameter parameter = new SqlParameter();

parameter.ParameterName = "@CategoryName";

parameter.SqlDbType = SqlDbType.NVarChar;

parameter.Direction = ParameterDirection.Input;

parameter.Value = categoryName;

// Add the parameter to the Parameters collection.

command.Parameters.Add(parameter);

// Open the connection and execute the reader.

connection.Open();

SqlDataReader reader = command.ExecuteReader();

if (reader.HasRows)

{

while (reader.Read())

{

Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);

}

}

else

{

Console.WriteLine("No rows found.");

}

reader.Close();

}

}

Generating Commands with CommandBuilders

When the SelectCommand property is dynamically specified at run time, such as through a query tool that

takes a textual command from the user, you may not be able to specify the appropriate InsertCommand,

UpdateCommand, or DeleteCommand at design time. If your DataTable maps to or is generated from a

single database table, you can take advantage of the DbCommandBuilder object to automatically

generate the DeleteCommand, InsertCommand, and UpdateCommand of the DbDataAdapter.

As a minimum requirement, you must set the SelectCommand property in order for automatic command

generation to work. The table schema retrieved by the SelectCommand property determines the syntax of

the automatically generated INSERT, UPDATE, and DELETE statements.

The DbCommandBuilder must execute the SelectCommand in order to return the metadata necessary to

construct the INSERT, UPDATE, and DELETE SQL commands. As a result, an extra trip to the data

source is necessary, and this can hinder performance. To achieve optimal performance, specify your

commands explicitly rather than using the DbCommandBuilder.

ADO.Net

47 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

The SelectCommand must also return at least one primary key or unique column. If none are present, an

InvalidOperation exception is generated, and the commands are not generated.

When associated with a DataAdapter, the DbCommandBuilder automatically generates the

InsertCommand, UpdateCommand, and DeleteCommand properties of the DataAdapter if they are null

references. If a Command already exists for a property, the existing Command is used.

Database views that are created by joining two or more tables together are not considered a single

database table. In this instance you cannot use the DbCommandBuilder to automatically generate

commands; you must specify your commands explicitly. For information about explicitly setting

commands to resolve updates to a DataSet back to the data source, see Updating Data Sources with

DataAdapters (ADO.NET).

You might want to map output parameters back to the updated row of a DataSet. One common task

would be retrieving the value of an automatically generated identity field or time stamp from the data

source. The DbCommandBuilder will not map output parameters to columns in an updated row by default.

In this instance you must specify your command explicitly. For an example of mapping an automatically

generated identity field back to a column of an inserted row, see Retrieving Identity or Autonumber

Values (ADO.NET).

The following table shows the rules for how automatically generated commands are generated.

Command Rule

InsertCommand Inserts a row at the data source for all rows in the table with a RowState of Added.

Inserts values for all columns that are updateable (but not columns such as

identities, expressions, or timestamps).

UpdateCommand Updates rows at the data source for all rows in the table with a RowState of

Modified. Updates the values of all columns except for columns that are not

updateable, such as identities or expressions. Updates all rows where the column

values at the data source match the primary key column values of the row, and

where the remaining columns at the data source match the original values of the

row..

DeleteCommand Deletes rows at the data source for all rows in the table with a RowState of Deleted.

Deletes all rows where the column values match the primary key column values of

the row, and where the remaining columns at the data source match the original

values of the row.

Limitations of Automatic Command Generation Logic

The following limitations apply to automatic command generation.

Unrelated Tables Only

The automatic command generation logic generates INSERT, UPDATE, or DELETE statements for

stand-alone tables without taking into account any relationships to other tables at the data source. As a

result, you may encounter a failure when calling Update to submit changes for a column that participates

ADO.Net

48 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

in a foreign key constraint in the database. To avoid this exception, do not use the DbCommandBuilder

for updating columns involved in a foreign key constraint; instead, explicitly specify the statements used

to perform the operation.

Table and Column Names

Automatic command generation logic fails if column names or table names contain any special

characters, such as spaces, periods, quotation marks, or other nonalphanumeric characters, even if

delimited by brackets. Fully qualified table names in the form of catalog.schema.table are supported.

Using the CommandBuilder to Automatically Generate an SQL Statement

To automatically generate SQL statements for a DataAdapter, first set the SelectCommand property of

the DataAdapter, then create a CommandBuilder object, and specify as an argument the DataAdapter for

which the CommandBuilder will automatically generate SQL statements.

// Assumes that connection is a valid SqlConnection object

// inside of a using block.

SqlDataAdapter adapter = new SqlDataAdapter( "SELECT * FROM dbo.Customers", connection);

SqlCommandBuilder builder = new SqlCommandBuilder(adapter);

builder.QuotePrefix = "[";

builder.QuoteSuffix = "]";

Modifying the SelectCommand

If you modify the CommandText of the SelectCommand after the INSERT, UPDATE, or DELETE

commands have been automatically generated, an exception may occur. If the modified

SelectCommand.CommandText contains schema information that is inconsistent with the

SelectCommand.CommandText used when the insert, update, or delete commands were automatically

generated, future calls to the DataAdapter.Update method may attempt to access columns that no longer

exist in the current table referenced by the SelectCommand, and an exception will be thrown.

You can refresh the schema information used by the CommandBuilder to automatically generate

commands by calling the RefreshSchema method of the CommandBuilder.

If you want to know what command was automatically generated, you can obtain a reference to the

automatically generated commands by using the GetInsertCommand, GetUpdateCommand, and

GetDeleteCommand methods of the CommandBuilder object and checking the CommandText property of

the associated command.

The following code example writes to the console the update command that was automatically generated.

Console.WriteLine(builder.GetUpdateCommand().CommandText)

The following example recreates the Customers table in the custDS dataset. The RefreshSchema

method is called to refresh the automatically generated commands with this new column information.

ADO.Net

49 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

// Assumes an open SqlConnection and SqlDataAdapter inside of a using block.

adapter.SelectCommand.CommandText = "SELECT CustomerID, ContactName FROM dbo.Customers";

builder.RefreshSchema();

custDS.Tables.Remove(custDS.Tables["Customers"]);

adapter.Fill(custDS, "Customers");

Obtaining a Single Value from a Database

You may need to return database information that is simply a single value rather than in the form of a

table or data stream. For example, you may want to return the result of an aggregate function such as

COUNT(*), SUM(Price), or AVG(Quantity). The Command object provides the capability to return single

values using the ExecuteScalar method. The ExecuteScalar method returns, as a scalar value, the

value of the first column of the first row of the result set.

The following code example inserts a new value in the database using a SqlCommand. The

ExecuteScalar method is used to return the identity column value for the inserted record.

static public int AddProductCategory(string newName, string connString)

{

Int32 newProdID = 0;

string sql =

"INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "

+ "SELECT CAST(scope_identity() AS int)";

using (SqlConnection conn = new SqlConnection(connString))

{

SqlCommand cmd = new SqlCommand(sql, conn);

cmd.Parameters.Add("@Name", SqlDbType.VarChar);

cmd.Parameters["@name"].Value = newName;

try

{

conn.Open();

newProdID = (Int32)cmd.ExecuteScalar();

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

}

return (int)newProdID;

}

Retrieving Data Example

ADO.Net

50 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

This example takes a DbConnection object as an argument. A DbCommand is created to select data from

the Categories table by setting the CommandText to a SQL SELECT statement. The code assumes that

the Categories table exists at the data source. The connection is opened and the data is retrieved using a

DbDataReader.

// Takes a DbConnection and creates a DbCommand to retrieve data

// from the Categories table by executing a DbDataReader.

static void DbCommandSelect(DbConnection connection)

{

string queryString = "SELECT CategoryID, CategoryName FROM Categories";

// Check for valid DbConnection.

if (connection != null)

{

using (connection)

{

try

{

// Create the command.

DbCommand command = connection.CreateCommand();

command.CommandText = queryString;

command.CommandType = CommandType.Text;

// Open the connection.

connection.Open();

// Retrieve the data.

DbDataReader reader = command.ExecuteReader();

while (reader.Read())

{

Console.WriteLine("{0}. {1}", reader[0], reader[1]);

}

}

catch (Exception ex)

{

Console.WriteLine("Exception.Message: {0}", ex.Message);

}

}

}

else

{

Console.WriteLine("Failed: DbConnection is null.");

}

}

ADO.Net

51 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Executing a Command Example

This example takes a DbConnection object as an argument. If the DbConnection is valid, the connection

is opened and a DbCommand is created and executed. The CommandText is set to a SQL INSERT

statement that performs an insert to the Categories table in the Northwind database. The code assumes

that the Northwind database exists at the data source, and that the SQL syntax used in the INSERT

statement is valid for the specified provider. Errors occurring at the data source are handled by the

DbException code block, and all other exceptions are handled in the Exception block.

DbCommand Class

Represents an SQL statement or stored procedure to execute against a data source. Provides a base

class for database-specific classes that represent commands.

Creating a DbCommand Object

The Data Access Application Block provides a consistent way to retrieve ADO.NET DbCommand

objects. The data access methods of the application block include overloads that accept a DbCommand

object. If you use the overloads with DbCommand objects, you have more control when you call stored

procedures. For example, if you use a DbCommand object, you can have a stored procedure that returns

several results in the output parameters. In addition, a DbCommand object allows you to specify the

stored procedure's timeout value.

The methods that create DbCommand objects are separated into two types:

Methods that represent stored procedure calls (for example, GetCustomers)

Methods that represent SQL text commands (for example, Select CustomerID, Fullname From

Customers)

The method you call to retrieve a DbCommand object is determined by whether you want to execute

inline SQL or call a stored procedure. The method that creates a DbCommand object for a stored

procedure also provides parameter caching. For more information about parameter caching, see

Handling Parameters.

All DbCommand objects are created using methods on the Database class. These methods are the

following:

GetStoredProcCommand. This method is for stored procedures commands.

GetSqlStringCommand. This method is for SQL text commands.

Both methods return a DbCommand object.

DbCommand Objects for SQL Statements

To create a DbCommand object for an inline SQL statement, use the GetSqlStringCommand method.

The specific SQL command to be executed is passed as an argument on the method call.

ADO.Net

52 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

The following code shows how to use GetSqlStringCommand.

Database db = DatabaseFactory.CreateDatabase();

string sql = "Select CustomerID, LastName, FirstName From Customers";

DbCommand cmd = db.GetSqlStringCommand(sql);

DbCommand Objects for Stored Procedures

To execute a stored procedure, you must use the GetStoredProcCommand method to create the

DbCommand object. The name of the stored procedure to be executed is passed as an argument to the

method.

The following code shows how to use GetStoredProcCommand.

Database db = DatabaseFactory.CreateDatabase();

DbCommand cmd = db.GetStoredProcCommand("GetProductsByCategory");

public abstract class DbCommand : Component, IDbCommand, IDisposable

Name Description

CanRaiseEvents Gets a value indicating whether the component can raise an event.

(Inherited from Component.)

CommandText Gets or sets the text command to run against the data source.

CommandTimeout Gets or sets the wait time before terminating the attempt to execute a

command and generating an error.

CommandType Indicates or specifies how the CommandText property is interpreted.

Connection Gets or sets the DbConnection used by this DbCommand.

Container Gets the IContainer that contains the Component. (Inherited from

Component.)

DbConnection Gets or sets the DbConnection used by this DbCommand.

DbParameterCollection Gets the collection of DbParameter objects.

DbTransaction Gets or sets the DbTransaction within which this DbCommand object

executes.

DesignMode

Gets a value that indicates whether the Component is currently in

ADO.Net

53 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

design mode. (Inherited from Component.)

Explicit Interface Implementations

Name Description

IDbCommand.Connection Gets or sets the IDbConnection used by

this instance of the IDbCommand.

IDbCommand.CreateParameter Creates a new instance of an

IDbDataParameter object.

IDbCommand.ExecuteReader Executes the CommandText against the

Connection and builds an IDataReader.

IDbCommand.ExecuteReader(CommandBehavior) Executes the CommandText against the

Connection, and builds an IDataReader

using one of the CommandBehavior

values.

IDbCommand.Parameters Gets the IDataParameterCollection.

IDbCommand.Transaction Gets or sets the DbTransaction within

which this DbCommand object executes.

Handling Data Errors with DbException

The DbException class is the base class for all exceptions thrown on behalf of a data source. You can

use it in your exception handling code to handle exceptions thrown by different providers without having

to reference a specific exception class. The following code fragment demonstrates how to use

DbException to display error information returned by the data source using GetType, Source, ErrorCode,

and Message properties. The output will display the type of error, the source indicating the provider

name, an error code, and the message associated with the error.

try

{

// Do work here.

ADO.Net

54 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

}

catch (DbException ex)

{

// Display information about the exception.

Console.WriteLine("GetType: {0}", ex.GetType());

Console.WriteLine("Source: {0}", ex.Source);

Console.WriteLine("ErrorCode: {0}", ex.ErrorCode);

Console.WriteLine("Message: {0}", ex.Message);

}

finally

{

// Perform cleanup here.

}

DataAdapters and DataReaders

You can use the ADO.NET DataReader to retrieve a read-only, forward-only stream of data from a

database. Results are returned as the query executes, and are stored in the network buffer on the client

until you request them using the Read method of the DataReader. Using the DataReader can increase

application performance both by retrieving data as soon as it is available, and (by default) storing only

one row at a time in memory, reducing system overhead.

A DataAdapter is used to retrieve data from a data source and populate tables within a DataSet. The

DataAdapter also resolves changes made to the DataSet back to the data source. The DataAdapter uses

the Connection object of the .NET Framework data provider to connect to a data source, and it uses

Command objects to retrieve data from and resolve changes to the data source.

Each .NET Framework data provider included with the .NET Framework has a DbDataReader and a

DbDataAdapter object: the .NET Framework Data Provider for OLE DB includes an OleDbDataReader

and an OleDbDataAdapter object, the .NET Framework Data Provider for SQL Server includes a

SqlDataReade and a SqlDataAdapter object, the .NET Framework Data Provider for ODBC includes an

OdbcDataReader and an OdbcDataAdapter object, and the .NET Framework Data Provider for Oracle

includes an OracleDataReaderOracleDataAdapter object.

The DataReader Object

The DataReader object provides a forward-only, read-only, connected stream recordset from a database.

Unlike other components of the Data Provider, DataReader objects cannot be directly instantiated.

Rather, the DataReader is returned as the result of the Command object's ExecuteReader method. The

SqlCommand.ExecuteReader method returns a SqlDataReader object, and the

OleDbCommand.ExecuteReader method returns an OleDbDataReader object. The DataReader can

provide rows of data directly to application logic when you do not need to keep the data cached in

memory. Because only one row is in memory at a time, the DataReader provides the lowest overhead in

terms of system performance but requires the exclusive use of an open Connection object for the lifetime

of the DataReader.

ADO.Net

55 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

The DataAdapter Object

The DataAdapter is the class at the core of ADO .NET's disconnected data access. It is essentially the

middleman facilitating all communication between the database and a DataSet. The DataAdapter is used

either to fill a DataTable or DataSet with data from the database with it's Fill method. After the memory-

resident data has been manipulated, the DataAdapter can commit the changes to the database by calling

the Update method. The DataAdapter provides four properties that represent database commands:

SelectCommand

InsertCommand

DeleteCommand

UpdateCommand

When the Update method is called, changes in the DataSet are copied back to the database and the

appropriate InsertCommand, DeleteCommand, or UpdateCommand is executed.

Retrieving Data Using a DataReader

Retrieving data using a DataReader involves creating an instance of the Command object and then

creating a DataReader by calling Command.ExecuteReader to retrieve rows from a data source. The

following example illustrates using a DataReader where reader represents a valid DataReader and

command represents a valid Command object.

reader = command.ExecuteReader();

You use the Read method of the DataReader object to obtain a row from the results of the query. You

can access each column of the returned row by passing the name or ordinal reference of the column to

the DataReader. However, for best performance, the DataReader provides a series of methods that

allow you to access column values in their native data types (GetDateTime, GetDouble, GetGuid,

GetInt32, and so on). For a list of typed accessor methods for data provider-specific DataReaders, see

OleDbDataReader and SqlDataReader. Using the typed accessor methods, assuming the underlying

data type is known, reduces the amount of type conversion required when retrieving the column value.

The following code example iterates through a DataReader object, and returns two columns from each

row.

static void HasRows(SqlConnection connection)

{

using (connection)

{

SqlCommand command = new SqlCommand("SELECT CategoryID, CategoryName FROM

Categories;", connection);

connection.Open();

SqlDataReader reader = command.ExecuteReader();

if (reader.HasRows)

{

ADO.Net

56 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

while (reader.Read())

{

Console.WriteLine("{0}\t{1}", reader.GetInt32(0),

reader.GetString(1));

}

}

else

{

Console.WriteLine("No rows found.");

}

reader.Close();

}

}

The DataReader provides an unbuffered stream of data that allows procedural logic to efficiently process

results from a data source sequentially. The DataReader is a good choice when retrieving large amounts

of data because the data is not cached in memory.

Closing the DataReader

You should always call the Close method when you have finished using the DataReader object.If your

Command contains output parameters or return values, they will not be available until the DataReader is

closed.

Note that while a DataReader is open, the Connection is in use exclusively by that DataReader. You

cannot execute any commands for the Connection, including creating another DataReader, until the

original DataReader is closed.

Do not call Close or Dispose on a Connection, a DataReader, or any other managed object in the

Finalize method of your class. In a finalizer, only release unmanaged resources that your class owns

directly. If your class does not own any unmanaged resources, do not include a Finalize method in your

class definition. For more information, see Garbage Collection.

Retrieving Multiple Result Sets using NextResult

If multiple result sets are returned, the DataReader provides the NextResult method to iterate through

the result sets in order. The following example shows the SqlDataReader processing the results of two

SELECT statements using the ExecuteReader method.

static void RetrieveMultipleResults(SqlConnection connection)

{

using (connection)

{

SqlCommand command = new SqlCommand(

"SELECT CategoryID, CategoryName FROM dbo.Categories;" +

"SELECT EmployeeID, LastName FROM dbo.Employees",

ADO.Net

57 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

connection);

connection.Open();

SqlDataReader reader = command.ExecuteReader();

while (reader.HasRows)

{

Console.WriteLine("\t{0}\t{1}", reader.GetName(0),

reader.GetName(1));

while (reader.Read())

{

Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0),

reader.GetString(1));

}

reader.NextResult();

}

}

}

Getting Schema Information from the DataReader

While a DataReader is open, you can retrieve schema information about the current result set using the

GetSchemaTable method. GetSchemaTable returns a DataTable object populated with rows and

columns that contain the schema information for the current result set. The DataTable contains one row

for each column of the result set. Each column of the schema table row maps to a property of the column

returned in the result set, where the ColumnName is the name of the property and the value of the

column is the value of the property. The following code example writes out the schema information for

DataReader.

static void GetSchemaInfo(SqlConnection connection)

{

using (connection)

{

SqlCommand command = new SqlCommand("SELECT CategoryID, CategoryName FROM

Categories;", connection);

connection.Open();

SqlDataReader reader = command.ExecuteReader();

DataTable schemaTable = reader.GetSchemaTable();

foreach (DataRow row in schemaTable.Rows)

{

foreach (DataColumn column in schemaTable.Columns)

{

Console.WriteLine(String.Format("{0} = {1}",

column.ColumnName, row[column]));

}

}

ADO.Net

58 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

}

}

The DbDataReader type exposes the following members.

Constructors

Name Description

DbDataReader Initializes a new instance of the DbDataReader class.

Properties

Name Description

Depth Gets a value indicating the depth of nesting for the current row.

FieldCount Gets the number of columns in the current row.

HasRows Gets a value that indicates whether this DbDataReader contains one or

more rows.

IsClosed Gets a value indicating whether the DbDataReader is closed.

Item(Int32) Gets the value of the specified column as an instance of Object.

Item(String) Gets the value of the specified column as an instance of Object.

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

SQL statement.

VisibleFieldCount Gets the number of fields in the DbDataReader that are not hidden.

Methods

Name Description

Close Closes the DbDataReader object.

CreateObjRef Creates an object that contains all the relevant information

ADO.Net

59 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

required to generate a proxy used to communicate with a

remote object. (Inherited from MarshalByRefObject.)

Dispose Releases all resources used by the current instance of the

DbDataReader class.

Dispose(Boolean) Releases the managed resources used by the DbDataReader

and optionally releases the unmanaged resources.

Equals(Object) Determines whether the specified Object is equal to the current

Object. (Inherited from Object.)

Finalize Allows an object to try to free resources and perform other

cleanup operations before it is reclaimed by garbage collection.

(Inherited from Object.)

GetBoolean Gets the value of the specified column as a Boolean.

GetByte Gets the value of the specified column as a byte.

GetBytes Reads a stream of bytes from the specified column, starting at

location indicated by dataOffset, into the buffer, starting at the

location indicated by bufferOffset.

GetChar Gets the value of the specified column as a single character.

GetChars Reads a stream of characters from the specified column,

starting at location indicated by dataIndex, into the buffer,

starting at the location indicated by bufferIndex.

GetData Returns a DbDataReader object for the requested column

ordinal.

GetDataTypeName Gets name of the data type of the specified column.

ADO.Net

60 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

GetDateTime Gets the value of the specified column as a DateTime object.

GetDbDataReader Returns a DbDataReader object for the requested column

ordinal that can be overridden with a provider-specific

implementation.

GetDecimal Gets the value of the specified column as a Decimal object.

GetDouble Gets the value of the specified column as a double-precision

floating point number.

GetEnumerator Returns an IEnumerator that can be used to iterate through the

rows in the data reader.

GetFieldType Gets the data type of the specified column.

GetFloat Gets the value of the specified column as a single-precision

floating point number.

GetGuid Gets the value of the specified column as a globally-unique

identifier (GUID).

GetHashCode Serves as a hash function for a particular type. (Inherited from

Object.)

GetInt16 Gets the value of the specified column as a 16-bit signed

integer.

GetInt32 Gets the value of the specified column as a 32-bit signed

integer.

GetInt64 Gets the value of the specified column as a 64-bit signed

integer.

ADO.Net

61 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

GetLifetimeService Retrieves the current lifetime service object that controls the

lifetime policy for this instance. (Inherited from

MarshalByRefObject.)

GetName Gets the name of the column, given the zero-based column

ordinal.

GetOrdinal Gets the column ordinal given the name of the column.

GetProviderSpecificFieldType Returns the provider-specific field type of the specified column.

GetProviderSpecificValue Gets the value of the specified column as an instance of Object.

GetProviderSpecificValues Gets all provider-specific attribute columns in the collection for

the current row.

GetSchemaTable Returns a DataTable that describes the column metadata of the

DbDataReader.

GetString Gets the value of the specified column as an instance of String.

GetType Gets the Type of the current instance. (Inherited from Object.)

GetValue Gets the value of the specified column as an instance of Object.

GetValues Populates an array of objects with the column values of the

current row.

InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for

this instance. (Inherited from MarshalByRefObject.)

IsDBNull Gets a value that indicates whether the column contains

nonexistent or missing values.

ADO.Net

62 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from

Object.)

MemberwiseClone(Boolean) Creates a shallow copy of the current MarshalByRefObject

object. (Inherited from MarshalByRefObject.)

NextResult Advances the reader to the next result when reading the results

of a batch of statements.

Read Advances the reader to the next record in a result set.

ToString Returns a string that represents the current object. (Inherited

from Object.)

Extension Methods

Name Description

AsParallel Enables parallelization of a query. (Defined by ParallelEnumerable.)

AsQueryable Converts an IEnumerable to an IQueryable. (Defined by Queryable.)

Cast(Of TResult) Converts the elements of an IEnumerable to the specified type. (Defined by

Enumerable.)

OfType(Of

TResult)

Filters the elements of an IEnumerable based on a specified type. (Defined

by Enumerable.)

Explicit Interface Implementations

Name Description

ADO.Net

63 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

IDataRecord.GetData For a description of this member, see IDataRecord.GetData.

DataSet from a DataAdapter

The ADO.NET DataSet is a memory-resident representation of data that provides a consistent relational

programming model independent of the data source. The DataSet represents a complete set of data that

includes tables, constraints, and relationships among the tables. Because the DataSet is independent of

the data source, a DataSet can include data local to the application, and data from multiple data sources.

Interaction with existing data sources is controlled through the DataAdapter.

The SelectCommand property of the DataAdapter is a Command object that retrieves data from the data

source. The InsertCommand, UpdateCommand, and DeleteCommand properties of the DataAdapter are

Command objects that manage updates to the data in the data source according to modifications made to

the data in the DataSet. These properties are covered in more detail in Updating Data Sources with

DataAdapters (ADO.NET).

The Fill method of the DataAdapter is used to populate a DataSet with the results of the SelectCommand

of the DataAdapter. Fill takes as its arguments a DataSet to be populated, and a DataTable object, or the

name of the DataTable to be filled with the rows returned from the SelectCommand.

The Fill method uses the DataReader object implicitly to return the column names and types that are

used to create the tables in the DataSet, and the data to populate the rows of the tables in the DataSet.

Tables and columns are only created if they do not already exist; otherwise Fill uses the existing DataSet

schema. Column types are created as .NET Framework types according to the tables in Data Type

Mappings in ADO.NET. Primary keys are not created unless they exist in the data source and

DataAdapter.MissingSchemaAction is set to MissingSchemaAction.AddWithKey. If Fill finds that a primary

key exists for a table, it will overwrite data in the DataSet with data from the data source for rows where

the primary key column values match those of the row returned from the data source. If no primary key is

found, the data is appended to the tables in the DataSet. Fill uses any mappings that may exist when you

populate the DataSet (see DataAdapter DataTable and DataColumn Mappings (ADO.NET)).

The following code example creates an instance of a SqlDataAdapter that uses a SqlConnection to the

Microsoft SQL Server Northwind database and populates a DataTable in a DataSet with the list of

customers. The SQL statement and SqlConnection arguments passed to the SqlDataAdapter constructor

are used to create the SelectCommand property of the SqlDataAdapter.

// Assumes that connection is a valid SqlConnection object.

string queryString =

"SELECT CustomerID, CompanyName FROM dbo.Customers";

SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);

ADO.Net

64 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

DataSet customers = new DataSet();

adapter.Fill(customers, "Customers");

Multiple Result Sets

If the DataAdapter encounters multiple result sets, it creates multiple tables in the DataSet. The tables are

given an incremental default name of TableN, starting with "Table" for Table0. If a table name is passed

as an argument to the Fill method, the tables are given an incremental default name of TableNameN,

starting with "TableName" for TableName0.

Notes

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

65 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

66 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

Disconnected Environment

In Disconnected environment, things are totally opposite to the connected environment; because users

will connect with the data source only to retrieve the data. When the data needs to be updated,

connection is re-established. User faces the data issue like data is not up to date.

We can differentiate the Connected and Disconnected environment on these major concepts As:

Connected Disconnected

Gives faster performance Slow in speed and performence.

Can hold the data of single table Can hold multiple tables of data

Forward only and readonly objects is not. Forward only and readonly objects

Needs connection to be created to access hence slower.

Data is in memory data that why faster access.

To access connected data you use ADO.NET Do not use ADO.Net.

Datareader treated as connected method. Dataset is disconnected method

.Net runtime creats an instance of the datatable to hold data.

Data can be accessed from multiple tables in a dataset.

You do not create a window in the form of a dataview used to sort and filter data.

you can create a window to the datatable in the form of a dataview used to sort and filter data.

You need to use a read only forward only data reader

You do not need to use a read only forward only data reader.

ADO.Net

67 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Data in a dataset can be deserialized.

Data in a dataset can be serialized

Code for disconnected architecture:

private void buttonshowdata_Click(object sender, EventArgs e)

{

SqlConnection con = new SqlConnection(connectionstring);

SqlDataAdapter adpt = new SqlDataAdapter("select * from Employee", con);DataSet ds = new

DataSet();

adpt.Fill(ds, "Employee");

dataGridView1.DataSource = ds;

dataGridView1.DataMember = "Employee";

}

Working with Datasets and Datatables between the tables.

There are several ways of working with a DataSet, which can be applied independently or in combination.

You can:

Programmatically create a DataTable, DataRelation, and Constraint within a DataSet and populate the

tables with data.

Populate the DataSet with tables of data from an existing relational data source using a DataAdapter.

Load and persist the DataSet contents using XML. For more information, see Using XML in a DataSet

(ADO.NET).

Creating a DataSet Object

There isn't anything special about instantiating a DataSet. You just create a new instance, just like any

other object:

DataSet dsCustomers = new DataSet();

Creating a DataSet

You create an instance of a DataSet by calling the DataSet constructor. Optionally specify a name argument. If you do not specify a name for the DataSet, the name is set to "NewDataSet". You can also create a new DataSet based on an existing DataSet. The new DataSet can be an exact copy of the existing DataSet; a clone of the DataSet that copies the relational structure or schema but that does not contain any of the data from the existing DataSet; or a subset of the DataSet, containing only the modified rows from the existing DataSet using the GetChanges method.

ADO.Net

68 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

The following code example demonstrates how to construct an instance of a DataSet.

DataSet customerOrders = new DataSet("CustomerOrders

Creating a SqlDataAdapter

The SqlDataAdapter holds the SQL commands and connection object for reading and writing data. You

initialize it with a SQL select statement and connection object:

SqlDataAdapter daCustomers = new SqlDataAdapter("select CustomerID, CompanyName from

Customers", conn);

Filling the DataSet

Once you have a DataSet and SqlDataAdapter instances, you need to fill the DataSet. Here's how to do

it, by using the Fill method of the SqlDataAdapter:

daCustomers.Fill(dsCustomers, "Customers");

Using the DataSet

A DataSet will bind with both ASP.NET and Windows forms DataGrids. Here's an example that assigns

the DataSet to a Windows forms DataGrid:

dgCustomers.DataSource = dsCustomers;

dgCustomers.DataMember = "Customers";

Updating Changes

After modifications are made to the data, you'll want to write the changes back to the database. Refer to

previous discussion in the Introduction of this article on update guidance. The following code shows how

to use the Update method of the SqlDataAdapter to push modifications back to the database.

daCustomers.Update(dsCustomers, "Customers");

Putting it All Together

Until now, you've seen the pieces required to implement disconnected data managment. What you really

need is to see all this implemented in an application. Listing 1 shows how the code from all the previous

sections is used in a working program that has been simplified to enhance the points of this lesson:

using System;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Windows.Forms;

class DisconnectedDataform : Form

{

private SqlConnection conn;

private SqlDataAdapter daCustomers;

private DataSet dsCustomers;

ADO.Net

69 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

private DataGrid dgCustomers;

private const string tableName = "Customers";

// initialize form with DataGrid and Button

public DisconnectedDataform()

{

// fill dataset

Initdata();

// set up datagrid

dgCustomers = new DataGrid();

dgCustomers.Location = new Point(5, 5);

dgCustomers.Size = new Size(

this.ClientRectangle.Size.Width - 10,

this.ClientRectangle.Height - 50);

dgCustomers.DataSource = dsCustomers;

dgCustomers.DataMember = tableName;

// create update button

Button btnUpdate = new Button();

btnUpdate.Text = "Update";

btnUpdate.Location = new Point(

this.ClientRectangle.Width/2 - btnUpdate.Width/2,

this.ClientRectangle.Height - (btnUpdate.Height + 10));

btnUpdate.Click += new EventHandler(btnUpdateClicked);

// make sure controls appear on form

Controls.AddRange(new Control[] { dgCustomers, btnUpdate });

}

// set up ADO.NET objects

public void Initdata()

{

// instantiate the connection

conn = new SqlConnection(

"Server=(local);DataBase=Northwind;Integrated Security=SSPI");

// 1. instantiate a new DataSet

dsCustomers = new DataSet();

// 2. init SqlDataAdapter with select command and connection

daCustomers = new SqlDataAdapter(

"select CustomerID, CompanyName from Customers", conn);

ADO.Net

70 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

// 3. fill in insert, update, and delete commands

SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daCustomers);

// 4. fill the dataset

daCustomers.Fill(dsCustomers, tableName);

}

// Update button was clicked

public void btnUpdateClicked(object sender, EventArgs e)

{

// write changes back to DataBase

daCustomers.Update(dsCustomers, tableName);

}

// start the Windows form

static void Main()

{

Application.Run(new DisconnectedDataForm());

}

}

PreserveChanges

When PreserveChanges is true, the data from the existing row is maintained in the Current row version of

the existing row, while the data from the Original row version of the existing row is overwritten with the

data from the Original row version of the incoming row. The RowState of the existing row is set to

Modified. The following exceptions apply:

If the existing row has a RowState of Deleted, this RowState remains Deleted and is not set to

Modified. In this case, the data from the incoming row will still be stored in the Original row version of

the existing row, overwriting the Original row version of the existing row (unless the incoming row has

a RowState of Added).

If the incoming row has a RowState of Added, the data from the Original row version of the existing

row will not be overwritten with data from the incoming row, because the incoming row does not have

an Original row version.When PreserveChanges is false, both the Current and Original row versions in

the existing row are overwritten with the data from the incoming row, and the RowState of the existing

row is set to the RowState of the incoming row. The following exceptions apply:

If the incoming row has a RowState of Unchanged and the existing row has a RowState of Modified,

Deleted, or Added, the RowState of the existing row is set to Modified.

ADO.Net

71 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

If the incoming row has a RowState of Added, and the existing row has a RowState of Unchanged,

Modified, or Deleted, the RowState of the existing row is set to Modified. Also, the data from the

Original row version of the existing row is not overwritten with data from the incoming row, because

the incoming row does not have an Original row version.

The following code example merges two DataSet objects with differents schemas into one DataSet with

the combined schemas of the two incoming DataSet objects.

using (SqlConnection connection = new SqlConnection(connectionString))

{

SqlDataAdapter adapter = new SqlDataAdapter("SELECT CustomerID, CompanyName FROM

dbo.Customers", connection);

connection.Open();

DataSet customers = new DataSet();

adapter.FillSchema(customers, SchemaType.Source, "Customers");

adapter.Fill(customers, "Customers");

DataSet orders = new DataSet();

orders.ReadXml("Orders.xml", XmlReadMode.ReadSchema);

orders.AcceptChanges();

customers.Merge(orders, true, MissingSchemaAction.AddWithKey);

Handling DataSet Events

The DataSet object provides three events: Disposed, Initialized and MergeFailed.

The MergeFailed Event

The following code fragment demonstrates how to add an event handler for the MergeFailed event.

workDS.MergeFailed += new MergeFailedEventHandler(DataSetMergeFailed);

private static void DataSetMergeFailed(object sender, MergeFailedEventArgs args)

{

Console.WriteLine("Merge failed for table " + args.Table.TableName);

Console.WriteLine("Conflict = " + args.Conflict);

}

The Initialized Event

The Initialized event occurs after the DataSet constructor initializes a new instance of the DataSet.

The IsInitialized property returns true if the DataSet has completed initialization; otherwise it returns false.

The Disposed Event

ADO.Net

72 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

DataSet is derived from the MarshalByValueComponent class, which exposes both the Dispose method

and the Disposed event. The Disposedevent adds an event handler to listen to the disposed event on the

component.

Related Topics

Term Definition

Validating Data in Datasets Provides an overview of events that can be used to analyze data

before the data is committed to a dataset.

How to: Implement Binding

Validation

Shows how to provide visual feedback to inform the user when an

invalid value is entered into a WPF control.

Data Binding Describes data binding in Silverlight controls, including a section on

data validation.

Validating Data Defined in

Conceptual Models

Describes how to validate data in Entity Framework and WCF Data

Services applications.

Typed DataSets

A typed DataSet is a class that derives from a DataSet. As such, it inherits all the methods, events, and

properties of a DataSet. Additionally, a typed DataSet provides strongly typed methods, events, and

properties.

DataTables

The DataTable class is a member of the System.Data namespace within the .NET Framework class

library. You can create and use a DataTable independently or as a member of a DataSet, and DataTable

objects can also be used in conjunction with other .NET Framework objects, including the DataView. You

access the collection of tables in a DataSet through the Tables property of the DataSet object.

Creating a DataTable

A DataTable, which represents one table of in-memory relational data, can be created and used

independently, or can be used by other .NET Framework objects, most commonly as a member of a

DataSet.

You can create a DataTable object by using the appropriate DataTable constructor. You can add it to the

DataSet by using the Add method to add it to the DataTable object's Tables collection.

You can also create DataTable objects within a DataSet by using the Fill or FillSchema methods of the

DataAdapter object, or from a predefined or inferred XML schema using the ReadXml,

ReadXmlSchema, or InferXmlSchema methods of the DataSet. Note that after you have added a

DataTable as a member of the Tables collection of one DataSet, you cannot add it to the collection of

tables of any other DataSet.

ADO.Net

73 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

The following example creates an instance of a DataTable object and assigns it the name "Customers."

DataTable workTable = new DataTable("Customers");

The following example creates an instance of a DataTable by adding it to the Tables collection of a

DataSet.

DataSet customers = new DataSet();

DataTable customersTable = customers.Tables.Add("CustomersTable");

DataTable Schema Definition

Handling DataTable Events

The DataTable object provides a series of events that can be processed by an application. The following

table describes DataTable events:

Event Description

Initialized Occurs after the EndInit method of a DataTable is called. This event is intended

primarily to support design-time scenarios.

ColumnChanged Occurs after a value has been successfully changed in a DataColumn.

ColumnChanging Occurs when a value has been submitted for a DataColumn.

RowChanged Occurs after a DataColumn value or the RowState of a DataRow in the DataTable has

been changed successfully.

RowChanging Occurs when a change has been submitted for a DataColumn value or the RowState

of a DataRow in the DataTable.

RowDeleted Occurs after a DataRow in the DataTable has been marked as Deleted.

RowDeleting Occurs before a DataRow in the DataTable is marked as Deleted.

TableCleared Occurs after a call to the Clear method of the DataTable has successfully cleared

every DataRow.

TableClearing Occurs after the Clear method is called but before the Clear operation begins.

ADO.Net

74 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

TableNewRow Occurs after a new DataRow is created by a call to the NewRow method of the

DataTable.

Disposed Occurs when the DataTable is Disposed. Inherited from MarshalByValueComponent.

Sequence of Operations

Here is the sequence of operations that occur when a DataRow is added, modified, or deleted:

1. Create the proposed record and apply any changes.

2. Check constraints for non-expression columns.

3. Raise the RowChanging or RowDeleting events as applicable.

4. Set the proposed record to be the current record.

5. Update any associated indexes.

6. Raise ListChanged events for associated DataView objects and PropertyChanged events for

associated DataRowView objects.

7. Evaluate all expression columns, but delay checking any constraints on these columns.

8. Raise ListChanged events for associated DataView objects and PropertyChanged events for

associated DataRowView objects affected by the expression column evaluations.

9. Raise RowChanged or RowDeleted events as applicable.

10. Check constraints on expression columns.

DataViews

A DataView enables you to create different views of the data stored in a DataTable, a capability that is

often used in data-binding applications. Using a DataView, you can expose the data in a table with

different sort orders, and you can filter the data by row state or based on a filter expression.

A DataView provides a dynamic view of data in the underlying DataTable: the content, ordering, and

membership reflect changes as they occur. This behavior differs from the Select method of the

DataTable, which returns a DataRow array from a table based on a particular filter and/or sort order:

thiscontent reflects changes to the underlying table, but its membership and ordering remain static. The

dynamic capabilities of the DataView make it ideal for data-binding applications.

Creating a DataView

There are two ways to create a DataView. You can use the DataView constructor, or you can create a

reference to the DefaultView property of the DataTable. The DataView constructor can be empty, or it

can take either a DataTable as a single argument, or a DataTable along with filter criteria, sort criteria,

and a row state filter

ADO.Net

75 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

The following code example demonstrates how to create a DataView using the DataView constructor. A

RowFilter, Sort column, and DataViewRowState are supplied along with the DataTable.

DataView custDV = new DataView(custDS.Tables["Customers"],

"Country = 'USA'", "ContactName", DataViewRowState.CurrentRows);

The following code example demonstrates how to obtain a reference to the default DataView of a

DataTable using the DefaultView property of the table.

DataView custDV = custDS.Tables["Customers"].DefaultView

The following table shows the options for DataViewRowState.

DataViewRowState

options

Description

CurrentRows The Current row version of all Unchanged, Added, and Modified rows.

This is the default.

Added The Current row version of all Added rows.

Deleted The Original row version of all Deleted rows.

ModifiedCurrent The Current row version of all Modified rows.

ModifiedOriginal The Original row version of all Modified rows.

None No rows.

OriginalRows The Original row version of all Unchanged, Modified, and Deleted rows.

Unchanged The Current row version of all Unchanged rows.

The following code example creates a view that shows all the products where the number of units in stock

is less than or equal to the reorder level, sorted first by supplier ID and then by product name.

DataView prodView = new DataView(prodDS.Tables["Products"],

"UnitsInStock <= ReorderLevel","SupplierID, ProductName",DataViewRowState.CurrentRows);

DataRows and DataRowViews

ADO.Net

76 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

A DataView exposes an enumerable collection of DataRowView objects. The DataRowView objects

expose values as object arrays that are indexed by either the name or the ordinal reference of the column

in the underlying table. You can access the DataRow that is exposed by the DataRowView by using the

Row property of the DataRowView.

The following code example displays all the current and original values in a table.

DataView catView = new DataView(catDS.Tables["Categories"]);

Console.WriteLine("Current Values:");

WriteView(catView);

Console.WriteLine("Original Values:");

catView.RowStateFilter = DataViewRowState.ModifiedOriginal;

WriteView(catView);

public static void WriteView(DataView thisDataView)

{

foreach (DataRowView rowView in thisDataView)

{

for (int i = 0; i < thisDataView.Table.Columns.Count; i++)

Console.Write(rowView[i] + "\t");

Console.WriteLine();

}

}

Modifying DataViews

The following code example disables using the DataView to delete rows and adds a new row to the

underlying table using the DataView.

DataTable custTable = custDS.Tables["Customers"];

DataView custView = custTable.DefaultView;

custView.Sort = "CompanyName";

custView.AllowDelete = false;

DataRowView newDRV = custView.AddNew();

newDRV["CustomerID"] = "ABCDE";

newDRV["CompanyName"] = "ABC Products";

newDRV.EndEdit();

Handling DataView Events

You can use the ListChanged event of the DataView to determine if a view has been updated. Updates

that raise the event include adding, deleting, or modifying a row in the underlying table; adding or deleting

a column to the schema of the underlying table; and a change in a parent or child relationship. The

ADO.Net

77 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

ListChanged event also notifies you if the list of rows you are viewing has changed significantly due to

the application of a new sort order or a filter.

The DataViewManager also exposes a ListChanged event to notify you if a table has been added or

removed, or if a change has been made to the Relations collection of the underlying DataSet.

The following code example shows how to add a ListChanged event handler.

custView.ListChanged += new System.ComponentModel.ListChangedEventHandler(OnListChanged);

protected static void OnListChanged(object sender, System.ComponentModel.ListChangedEventArgs

args)

{

Console.WriteLine("ListChanged:");

Console.WriteLine("\t Type = " + args.ListChangedType);

Console.WriteLine("\tOldIndex = " + args.OldIndex);

Console.WriteLine("\tNewIndex = " + args.NewIndex);

}

Creating a DataTable from a DataView

you can use the ToTable method to copy all the rows and columns, or a subset of the data into a new

DataTable. The ToTable method provides overloads to:

Create a DataTable containing columns that are a subset of the columns in the DataView.

Create a DataTablethat includes only distinct rows from the DataView, analogously to the

DISTINCT keyword in Transact-SQL.

Activity: Disconnected Environment

1. Mr. Richard, HR Member of Marvin & Company, needs to store the details of employees who

have recently joined the organization. You need to create an application for Richard that will

enable him to add and save the details of new employee and if required, delete records of

employees who are no longer working in the organization. The employee code should get

automatically generated based on the format in the table. The employee details will be stored

in the empdetails table of the HR database.

ADO.Net

78 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Notes

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

79 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

80 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

81 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Handling Database Features

As a programmer, you need to ensure that your applications are robust to support advance database

operations. This may entail storing and retrievinf larger-sized objects like images and standard format

documents such as XML documents, copying hundreds of records from one table to another, caching the

records of a database, and ebsuring that the cache maintains updated records. You also need to ensure

that your application has optimum performance. You can do so by using advanced database features in

ADO.NET.

Handling Binary Larger Objects in a Database.

LOB are of different formats, such as:

Binary Large Objects(BLOB): If a LOB is stored in a database in binary format, it is referred to as

BLOB.

Character Large Object(CLOB): If a LOB is stored in the database in a textual format, it is referred to as

CLOB.

Retrieving Large Data

By default, the DataReader loads incoming data as a row as soon as an entire row of data is available.

Binary large objects (BLOBs) need different treatment, however, because they can contain gigabytes of

data that cannot be contained in a single row. The Command.ExecuteReader method has an overload

that will take a CommandBehavior argument to modify the default behavior of the DataReader. You can

pass SequentialAccess to the ExecuteReader method to modify the default behavior of the DataReader

so that instead of loading rows of data, it will load data sequentially as it is received. This is ideal for

loading BLOBs or other large data structures. Note that this behavior may depend on your data source.

For example, returning a BLOB from Microsoft Access will load the entire BLOB being loaded into

memory, rather than sequentially as it is received.

Example:

The following example returns the publisher ID and logo from the pubs sample database in Microsoft

SQL Server 2000. The publisher ID (pub_id) is a character field, and the logo is an image, which is a

BLOB. Because the logo field is a bitmap, the example returns binary data using GetBytes. Notice that

the publisher ID is accessed for the current row of data before the logo, because the fields must be

accessed sequentially.

// Assumes that connection is a valid SqlConnection object.

SqlCommand command = new SqlCommand("SELECT pub_id, logo FROM pub_info", connection);

// Writes the BLOB to a file (*.bmp).

FileStream stream;

// Streams the BLOB to the FileStream object.

BinaryWriter writer;

ADO.Net

82 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

// Size of the BLOB buffer.

int bufferSize = 100;

// The BLOB byte[] buffer to be filled by GetBytes.

byte[] outByte = new byte[bufferSize];

// The bytes returned from GetBytes.

long retval;

// The starting position in the BLOB output.

long startIndex = 0;

// The publisher id to use in the file name.

string pubID = "";

// Open the connection and read data into the DataReader.

connection.Open();

SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess);

while (reader.Read())

{

// Get the publisher id, which must occur before getting the logo.

pubID = reader.GetString(0);

// Create a file to hold the output.

stream = new FileStream("logo" + pubID + ".bmp", FileMode.OpenOrCreate, FileAccess.Write);

writer = new BinaryWriter(stream);

// Reset the starting byte for the new BLOB.

startIndex = 0;

// Read bytes into outByte[] and retain the number of bytes returned.

retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);

// Continue while there are bytes beyond the size of the buffer.

while (retval == bufferSize)

{

writer.Write(outByte);

writer.Flush();

// Reposition start index to end of last buffer and fill buffer.

startIndex += bufferSize;

retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);

}

// Write the remaining buffer.

ADO.Net

83 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

writer.Write(outByte, 0, (int)retval - 1);

writer.Flush();

// Close the output file.

writer.Close();

stream.Close();

}

// Close the reader and the connection.

reader.Close();

connection.Close();

Storing BLOB Data

To store a BLOB, an application must call an remote BLOB store (RBS) client library API with the

following information on the BLOB to be stored:

A connection to the database that the BLOB data will be stored in.

A collection ID.

Optional command options that specify additional information on how the BLOB will be stored.

The following steps describe how to store a BLOB in RBS. This example assumes that the SQL collection

was created with the appropriate policy and configuration settings, and that the collection ID is stored by

the application.

To store a BLOB

1. Establish an active SQL connection to the database in which the BLOB will be stored and the RBS

context.

2. Determine the collection ID value of the collection in which the blob will be stored. Collections allow

applications to manage different groups of BLOBs inside a single database.

3. Create a SqlRemoteBlob object that represents the BLOB data on the BLOB context by calling

CreateNewBlob. You may configure the SqlRemoteBlob by specifying command options, such as

setting the BlobStoreName, in an optional ConfigItemList parameter.

4. Store the BLOB data in the BLOB store by pushing or pulling the BLOB data. The following sections

describe how to perform these operations in greater detail.

5. Store the BlobId property of the SqlRemoteBlob object in the RBS column of the application table.

Dispose the SqlRemoteBlob object

Reading BLOB Data

To read BLOB data

1. Establish a SqlRemoteBlobContext.

ADO.Net

84 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

2. Determine the BlobID value of the blob to read. This ID is stored in the RBS column of the

applications table.

3. Create a SqlRemoteBlob object by calling the OpenBlob method with the specified BlobId of the

BLOB data to be read.

4. Read the BLOB data by pulling it from a stream provided by RBS, or by specifying a stream into which

RBS can push BLOB data.

Example:

The following code example demonstrates how to pull BLOB data from a stream:

void RunFetchStreamPull(string connectionString)

{

// Create and open a new SqlConnection

using (SqlConnection conn = new SqlConnection(connectionString))

{

conn.Open();

// Create a blob context for RBS to operate within.

using (SqlRemoteBlobContext blobContext = new SqlRemoteBlobContext(conn))

{

// Get the BLOB with the specified BlobId.

string queryBlobEntry = @" select BlobId from ApplicationSampleTable

where

SearchTags LIKE '%Sample%' ";

DataTable blobIds = new DataTable();

blobIds.Locale = CultureInfo.InvariantCulture;

// Run a query to fetch all of the BLOB IDs.

using (SqlCommand cmd = new SqlCommand(queryBlobEntry, conn))

{

// Fill the blob references and close the command.

using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))

{

adapter.Fill(blobIds);

}

}

// Cycle through all the returned rows and process each

// one in turn.

Console.WriteLine("Reading blob data (Stream Pull):");

foreach (DataRow dr in blobIds.Rows)

{

ADO.Net

85 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

// Get the BlobId

byte[] blobId = (byte[])dr[0];

// Get a stream containing the BLOB data with the

// specified ID

using (SqlRemoteBlob blob = blobContext.OpenBlob(blobId))

{

// Read the contents of the BLOB stream by

// pulling it into a buffer, which is then

// output to the console.

byte[] readdata = new byte[256];

blob.Read(readdata, 0, readdata.Length);

Console.WriteLine(Encoding.Unicode.GetString(readdata));

}

}

}

}

}

}

Activity: Handling Database Features

1. Write program to solve this problem, where a new employee has joined the Marvin & Company. The details of this employee need to be inserted in the Employee table. The details are as follow:

Employee code : 0A1234

First Name : Andrew

Last Name : Methu In addition, the photograph of the employee should be uploaded to the database. It should be displayed after the photograph is inserted. Create an application that will perform the required task like this.

ADO.Net

86 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

ADO.Net

87 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Notes

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

88 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

89 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

90 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Performing Bulk Copy Features

There can be a situation when you need to copy a large amount of data from on location to another. The

SQL Server bulk copy feature supports the transfer of large amounts of data into or out of a SQL Server

table or view. Data can also be transferred out by specifying a SELECT statement. The data can be

moved between SQL Server and an operating-system data file, such as an ASCII file. The data file can

have different formats; the format is defined to bulk copy in a format file. Optionally, data can be loaded

into program variables and transferred to SQL Server using bulk copy functions and methods.

An application typically uses bulk copy in one of the following ways:

Bulk copy from a table, view, or the result set of a Transact-SQL statement into a data file where the

data is stored in the same format as the table or view.

This is called a native-mode data file.

Bulk copy from a table, view, or the result set of a Transact-SQL statement into a data file where the

data is stored in a format other than the one of the table or view.

In this case, a separate format file is created that defines the characteristics (data type, position, length,

terminator, and so on) of each column as it is stored in the data file. If all columns are converted to

character format, the resulting file is called a character-mode data file.

Bulk copy from a data file into a table or view.

If needed, a format file is used to determine the layout of the data file.

Load data into program variables, and then import the data into a table or view using the bulk

copy functions for bulk copying in a row at a time.

Bulk copying of data from one data source to another data source is a new feature added to ADO.NET.

Bulk copy classes provide the fastest way to transfer set of data from once source to the other.

Each ADO.NET data provider provides bulk copy classes. For example, in SQL .NET data provider, the

bulk copy operation is handled by SqlBulkCopy class, which is described in below figure. As you can see

from this Figure, data from a data source can be copied to one of the four types - DataReader, DataSet,

DataTable, or XML.

ADO.Net

91 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Using bulk copy operation, you can transfer data between two tables on the same SQL Server, between

two different SQL Servers, or even two different types of database servers.

SQL Server Native Client OLE DB Provider

Using Memory Based Bulk Copy Operations

Enabling a Session for IRowsetFastLoad

Enabling a session for bulk copy constrains the SQL Server Native Client OLE DB provider support for

interfaces on the session. A bulk copy-enabled session exposes only the following interfaces:

IDBSchemaRowset

IGetDataSource

IOpenRowset

ISupportErrorInfo

ITransactionJoin

IRowsetFastLoad Rowsets

The SQL Server Native Client OLE DB provider bulk copy rowsets are write-only, but they expose

interfaces that allow the consumer to determine the structure of a SQL Server table. The following

interfaces are exposed on a bulk copy-enabled SQL Server Native Client OLE DB provider rowset:

IAccessor

IColumnsInfo

IColumnsRowset

IConvertType

IRowsetFastLoad

IRowsetInfo

ISupportErrorInfo

SQL Server Native Client ODBC Driver

The SQL Server Native Client ODBC driver maintains the same support for bulk copy operations that were part of previous versions of the SQL Server ODBC driver.

Managing Bulk Copy Batch Sizes

The primary purpose of a batch in bulk copy operations is to define the scope of a transaction. If a batch

size is not set, then bulk copy functions consider an entire bulk copy to be one transaction. If a batch size

is set, then each batch constitutes a transaction that is committed when the batch finishes.

ADO.Net

92 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

The number of rows making up a batch can have significant performance effects when bulk copying a

large number of rows. The recommendations for batch size depend on the type of bulk copy being

performed.

When bulk copying to SQL Server, specify the TABLOCK bulk copy hint and set a large batch size.

When TABLOCK is not specified, limit batch sizes to less than 1,000 rows.

Performing a Single Bulk Copy Operation

The general steps for performing a bulk copy operation are as follows:

1. Connect to the source server and obtain the data to be copied. Data can also come from other

sources, if it can be retrieved from an IDataReader or DataTable object.

2. Connect to the destination server (unless you want SqlBulkCopy to establish a connection for

you).

3. Create a SqlBulkCopy object, setting any necessary properties.

4. Set the DestinationTableName property to indicate the target table for the bulk insert operation.

5. Call one of the WriteToServer methods.

6. Optionally, update properties and call WriteToServer again as necessary.

7. Call Close, or wrap the bulk copy operations within a Using statement.

Performing a Bulk Copy Operation

The following example illustrates how to use the ExecuteNonQuery method to execute the BULK INSERT

statement.

using (SqlConnection connection = New SqlConnection(connectionString))

{

string queryString = "BULK INSERT Northwind.dbo.[Order Details] " +

"FROM 'f:\mydata\data.tbl' " +

"WITH ( FORMATFILE='f:\mydata\data.fmt' )";

connection.Open();

SqlCommand command = new SqlCommand(queryString, connection);

command.ExecuteNonQuery();

}

ADO.Net

93 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Multiple Bulk Copy Operations

You can perform multiple bulk copy operations using a single instance of a SqlBulkCopy class. If the

operation parameters change between copies (for example, the name of the destination table), you must

update them prior to any subsequent calls to any of the WriteToServer methods, as demonstrated in the

following example. Unless explicitly changed, all property values remain the same as they were on the

previous bulk copy operation for a given instance.

using System.Data.SqlClient;

class Program

{

static void Main()

{

string connectionString = GetConnectionString();

// Open a connection to the AdventureWorks database.

using (SqlConnection connection =new SqlConnection(connectionString))

{

connection.Open();

// Empty the destination tables.

SqlCommand deleteHeader = new SqlCommand(

"DELETE FROM dbo.BulkCopyDemoOrderHeader;",connection);

deleteHeader.ExecuteNonQuery();

SqlCommand deleteDetail = new SqlCommand(

"DELETE FROM dbo.BulkCopyDemoOrderDetail;", connection);

deleteDetail.ExecuteNonQuery();

// Perform an initial count on the destination

// table with matching columns.

SqlCommand countRowHeader = new SqlCommand(

"SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", connection);

long countStartHeader = System.Convert.ToInt32(countRowHeader.ExecuteScalar());

Console.WriteLine("Starting row count for Header table = {0}", countStartHeader);

// Perform an initial count on the destination

// table with different column positions.

SqlCommand countRowDetail = new SqlCommand(

"SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;",connection);

long countStartDetail = System.Convert.ToInt32(countRowDetail.ExecuteScalar());

Console.WriteLine( "Starting row count for Detail table = {0}",countStartDetail);

// Get data from the source table as a SqlDataReader.

ADO.Net

94 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

// The Sales.SalesOrderHeader and Sales.SalesOrderDetail

// tables are quite large and could easily cause a timeout

// if all data from the tables is added to the destination.

// To keep the example simple and quick, a parameter is

// used to select only orders for a particular account

// as the source for the bulk insert.

SqlCommand headerData = new SqlCommand("SELECT [SalesOrderID], [OrderDate], " +

"[AccountNumber] FROM [Sales].[SalesOrderHeader] " +

"WHERE [AccountNumber] = @accountNumber;",connection);

SqlParameter parameterAccount = new SqlParameter();

parameterAccount.ParameterName = "@accountNumber";

parameterAccount.SqlDbType = SqlDbType.NVarChar;

parameterAccount.Direction = ParameterDirection.Input;

parameterAccount.Value = "10-4020-000034";

headerData.Parameters.Add(parameterAccount);

SqlDataReader readerHeader = headerData.ExecuteReader();

// Get the Detail data in a separate connection.

using (SqlConnection connection2 = new SqlConnection(connectionString))

{

connection2.Open();

SqlCommand sourceDetailData = new SqlCommand(

"SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " +

"[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " +

"INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." +

"[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " +

"WHERE [AccountNumber] = @accountNumber;", connection2);

SqlParameter accountDetail = new SqlParameter();

accountDetail.ParameterName = "@accountNumber";

accountDetail.SqlDbType = SqlDbType.NVarChar;

accountDetail.Direction = ParameterDirection.Input;

accountDetail.Value = "10-4020-000034";

sourceDetailData.Parameters.Add(accountDetail);

SqlDataReader readerDetail = sourceDetailData.ExecuteReader();

// Create the SqlBulkCopy object.

using (SqlBulkCopy bulkCopy =

new SqlBulkCopy(connectionString))

{

bulkCopy.DestinationTableName =

"dbo.BulkCopyDemoOrderHeader";

// Guarantee that columns are mapped correctly by

ADO.Net

95 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

// defining the column mappings for the order.

bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID");

bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate");

bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber");

// Write readerHeader to the destination.

try

{

bulkCopy.WriteToServer(readerHeader);

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

finally

{

readerHeader.Close();

}

// Set up the order details destination.

bulkCopy.DestinationTableName ="dbo.BulkCopyDemoOrderDetail";

// Clear the ColumnMappingCollection.

bulkCopy.ColumnMappings.Clear();

// Add order detail column mappings.

bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID");

bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID");

bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty");

bulkCopy.ColumnMappings.Add("ProductID", "ProductID");

bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice");

// Write readerDetail to the destination.

try

{

bulkCopy.WriteToServer(readerDetail);

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

finally

{

ADO.Net

96 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

readerDetail.Close();

}

}

// Perform a final count on the destination

// tables to see how many rows were added.

long countEndHeader = System.Convert.ToInt32(

countRowHeader.ExecuteScalar());

Console.WriteLine("{0} rows were added to the Header table.",

countEndHeader - countStartHeader);

long countEndDetail = System.Convert.ToInt32(

countRowDetail.ExecuteScalar());

Console.WriteLine("{0} rows were added to the Detail table.",

countEndDetail - countStartDetail);

Console.WriteLine("Press Enter to finish.");

Console.ReadLine();

}

}

}

private static string GetConnectionString()

// To avoid storing the connection string in your code,

// you can retrieve it from a configuration file.

{

return "Data Source=(local); " +

" Integrated Security=true;" +

"Initial Catalog=AdventureWorks;";

}

}

Activity: Delegates

1. The employee details of Marvin & Company are stored in the Employees table of the HR

database. The records of this table have got deleted accidently. However, a backup copy of

the table is available. This table is named as EmployeeBackUp. The records from the

EmployeeBackUp table need to be copied to the Empoyees table.

You are the developer in the company, so you have been told to create an application that will

copy the records from EmployeeBackUp to Employees table. Create an application that will

perform the required task in the shortest possible time.

ADO.Net

97 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

ADO.Net

98 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Notes

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

99 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

100 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

101 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

SQL Notification

SQL Server Notification Services is a platform developed by Microsoft for the development and

deployment of notification applications based on SQL Server Technology and the Microsoft.NET

Framework. Notification Services offers a scalable server engine on which to run notification applications,

with multi-server capability-providing flexibility and scalability for deploying applications.

Notification Services was designed to ease the pain of developing and deploying notification applications

that generate personalized, timely information to subscribers.

There are three ways you can implement query notifications using ADO.NET:

1. The low-level implementation is provided by the SqlNotificationRequest class that exposes server-

side functionality, enabling you to execute a command with a notification request.

2. The high-level implementation is provided by the SqlDependency class, which is a class that provides

a high-level abstraction of notification functionality between the source application and SQL Server,

enabling you to use a dependency to detect changes in the server. In most cases, this is the simplest

and most effective way to leverage SQL Server notifications capability by managed client applications

using the .NET Framework Data Provider for SQL Server.

3. In addition, Web applications built using ASP.NET 2.0 or later can use the SqlCacheDependency

helper classes.

Enabling Query Notifications

Applications that consume query notifications have a common set of requirements. Your data source

must be correctly configured to support SQL query notifications, and the user must have the correct

client-side and server-side permissions.

To use query notifications you must:

Use SQL Server 2005 or SQL Server 2008.

Enable query notifications for your database.

Ensure that the user ID used to connect to the database has the necessary permissions.

Use a SqlCommandobject to execute a valid SELECT statement with an associated notification

object—either SqlDependency or SqlNotificationRequest.

Provide code to process the notification if the data being monitored changes.

Enabling Query Notifications to Run:

To enable Service Broker on the AdventureWorks database by using SQL Server Management

Studio, execute the following Transact-SQL statement:

ADO.Net

102 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

ALTER DATABASE AdventureWorks SET ENABLE_BROKER;

For the query notification samples to run correctly, the following Transact-SQL statements must

be executed on the database server.

// Code requires directives to

// System.Security.Permissions and

// System.Data.SqlClient

private bool CanRequestNotifications()

{

SqlClientPermission permission = new SqlClientPermission( PermissionState.Unrestricted);

try

{

permission.Demand();

return true;

}

catch (System.Exception)

{

return false;

}

}

Choosing a Notification Object

The query notifications API provides two objects to process notifications: SqlDependency and

SqlNotificationRequest. In general, most non-ASP.NET applications should use the SqlDependency

object. ASP.NET applications should use the higher-level SqlCacheDependency, which wraps

SqlDependency and provides a framework for administering the notification and cache objects.

Using SqlDependency

To use SqlDependency, Service Broker must be enabled for the SQL Server database being used, and

users must have permissions to receive notifications. Service Broker objects, such as the notification

queue, are predefined.

Creating the Notification Request

You can use a SqlNotificationRequest object to create the notification request by binding it to a

SqlCommand object. Once the request is created, you no longer need the SqlNotificationRequest object.

You can query the queue for any notifications and respond appropriately. Notifications can occur even if

the application is shut down and subsequently restarted.

ADO.Net

103 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

When the command with the associated notification is executed, any changes to the original result set

trigger sending a message to the SQL Server queue that was configured in the notification request.

Example

The following code fragment demonstrates how to create a SqlNotificationRequest and associate it with

a SqlCommand.

// Assume connection is an open SqlConnection.

// Create a new SqlCommand object.

SqlCommand command=new SqlCommand("SELECT ShipperID, CompanyName, Phone FROM

dbo.Shippers", connection);

// Create a SqlNotificationRequest object.

SqlNotificationRequest notficationRequest=new SqlNotificationRequest();

notficationRequest.id="NotificationID";

notficationRequest.Service="mySSBQueue";

// Associate the notification request with the command.

command.Notification=notficationRequest;

// Execute the command.

command.ExecuteReader();

// Process the DataReader.

// You can use Transact-SQL syntax to periodically poll the

// SQL Server queue to see if you have a new message.

Step-By-Step approach in implementing Query Notifications

The whole process of request-receive notification process between the client windows application and the

SQL Server 2005 is done in five little steps as follows:

1. The database that is in question must be configured to enable query notification services.

For security reasons, SQL Server 2005 databases do not have Service Broker enabled by default. To

enable query notifications for your database, in the SQL SERVER 2005 MAnagement Studio, Query

window, run the following command:

ALTER DATABASE SET ENABLE_BROKER;

In this article, I uses the database named AdvtDB

ALTER DATABASE AdvtDB SET ENABLE_BROKER;

2. The user must have the correct client and server side permissions to request and receive

notifications.

ADO.Net

104 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Users who execute commands requesting notification must have SUBSCRIBE QUERY

NOTIFICATIONS database permission on the server.Client-side code that runs in a partial trust

situation requires the SqlClientPermission.

private bool EnoughPermission()

{

SqlClientPermission perm = new

SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);

try

{

perm.Demand();

return true;

}

catch (System.Exception)

{

return false;

}

}

3. Use a SqlCommand object to execute a valid SELECT statement with an associated

notification object—SqlDependency.

SqlDependency Object The query notifications API provides SqlDependency object to process

notifications. When using SqlDependency, Service Broker objects, such as the notification queue, are

predefined. It automatically launches a worker thread to process notifications as they are posted to

the queue; it also parses the Service Broker message, exposing the information as event argument

data. SqlDependency must be initialized by calling the Start method to establish a dependency to the

database. This is a static method that need be called only once during application initialization for

each database connection required. The Stop method should be called at application termination for

each dependency connection that was made.

On Click of a button, database connection is established, SqlDependency is started to listen the

notification service and a DataGridView Control is displayed with current results returned from a

query executed by the command object.

private void button1_Click(object sender, EventArgs e)

{

// Remove any existing dependency connection, then create a new one.

connstr = “Data Source=localhost;Integrated Security=SSPI;Initial Catalog=AdvtDB;”;

string ssql = “select * from advt “;

SqlDependency.Stop(connstr);

SqlDependency.Start(connstr);

if (connection == null)

connection = new SqlConnection(connstr);

if (command == null)

ADO.Net

105 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

command = new SqlCommand(ssql , connection);

if (myDataSet == null)

myDataSet = new DataSet();

GetAdvtData();

}

GetAdvtData() is a helper function that creates the command object instance, associate it with the

SqlDependency object. Note that the SqlDependency object has an OnChange event notifying the client

that changes has been done in the database and its eventhandler dependency_OnChange will take care

of the receiving part of the notification.

private void GetAdvtData()

{

myDataSet.Clear();

// Make sure the command object does not already have a notification object associated with it.

command.Notification = null;

// Create and bind the SqlDependency object to the command object.

SqlDependency dependency =new SqlDependency(command);

dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

using (SqlDataAdapter adapter = new SqlDataAdapter(command))

{

adapter.Fill(myDataSet, “Advt”);

dataGridView1.DataSource = myDataSet;

dataGridView1.DataMember = “Advt”;

}

}

4. Provide code to process the notification when and if the data being monitored changes.

The worker thread process encapsulates the OnChange Event handler and hence, the UI

changes(updating the datagrid, displaying the status message) available in the Main thread might not

be accessible here. Create another delegate thread UIDelegate that does these tasks and let the

worker thread removes just the handler from the OnChange event of the SqlDependency object.

delegate void UIDelegate();

private void dependency_OnChange(object sender, SqlNotificationEventArgs e)

{

UIDelegate uidel = new UIDelegate(RefreshData);

this.Invoke(uidel, null);

//Remove the handler as it is used for a single notification.

SqlDependency dependency =(SqlDependency)sender;

dependency.OnChange -= dependency_OnChange;

ADO.Net

106 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

}

private void RefreshData()

{

// At this point, the code is executing on the UI thread, so it is safe to update the UI.

label1.Text = “Database had some changes and are applied in the Grid”;

// Reload the dataset that is bound to the grid.

GetAdvtData();

}

5. Stop the SqlDependency Notification Services while quitting the application.

In the form_closing event, you include the code for stopping the SqlDepenency notification listener

service.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)

{

SqlDependency.Stop(connstr);

if (connection != null)

connection.Close();

}

Following are the declarations used in this program.

private const string statusMessage;

private DataSet myDataSet = null;

private SqlConnection connection = null;

private SqlCommand command = null;

private string connstr;

Testing the application

Run the C# Windows application you have just created following the above steps. When the form shows up, Click the button and notice that your datagridview control is populated.

Now, Open the Query window of the SQL Server Management studio, and insert rows or update columns in the table concerned. When you switch back to your C# running application, you could see the changes appeared in the datagrid view.

Activity: SQL Notification

1. The details of the various positions in Marvin & Company are stored in a position table, which

is maintained by the HR management team. This table has the following fields:

Position code

Description

Budgeted strength

ADO.Net

107 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Year

Current strength

The budgeted strength and the current strength fields of this table are frequently modified. As

a result, the management of Marvin & Company has decided to cache the records of this table.

Create an application that will notify the vacancy initiation application about any change in

values of these two fields for the current year.

ADO.Net

108 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

Notes

…………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

ADO.Net

109 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

110 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

ADO.Net

111 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

112 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

…………………………………………………………………………………………………………………………

ADO.Net

113 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date:

What did I learn? How will I implement it?

ADO.Net

114 ©2011 by Shriram Value Services Pvt.Ltd. Reproduction of this manual in any form copying, printing & publishing is prohibited. This manual

is meant exclusively for Training purposes & not meant for sale.

Document Version:Release Date: