Вы находитесь на странице: 1из 51

DOT Net Technologies

Unit 7

Unit 7
Structure: 7.1 Introduction Objectives 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 7.10 Connecting to a Data Source using ADO.NET Connection Strings using ADO.NET Connection String Builders (ADO.NET) Building Connection Strings from Configuration Files Basic ADO.NET Features ADO.NET Namespaces and Classes Fetching the data: DataAdapter XML & ADO.NET Summary Self Assessment Questions 7.11 7.12 Terminal Questions Answers to Self Assessment Questions

ADO.NET

7.1 Introduction
What is ADO.NET? The ADO.NET has been developed to enhance the creation of powerful and scalable web applications, by working with data in a disconnected way under the .Net frameworks stateless distributed web model. It has been specifically designed to operate in a 3-tier environment. As the ADO.NET operates in a disconnected way, no longer remaining connected to the data server while performing positional updates, there is a far great scope for data manipulation. ADO.NET was first introduced in version 1.0 of the .NET framework, that provided an extensive array of features to handle live data in a connected
Sikkim Manipal University Page No. 204

DOT Net Technologies

Unit 7

mode or data that is disconnected from its underlying data store. Today with the explosion of the Internet as a means of data communication, a new data technology is required to make data accessible and updateable in a disconnected architecture. Data Access Scenarios: 1. The most popular data access scenario in the Internet is the one in which a user must locate a collection of data and iterate through this data a single time. When a request for data from a Web page that you have created is received, you can simply fill a table with data from a data store. In this case, you go to the data store, grab the data that you want, send the data across the wire, and then populate the table. In this scenario the goal is to get the data as fast as possible. 2. The second way to work with data in a disconnected architecture is to grab a collection of data and use this data separately from the data store itself. This data could be either on the client machine or the server machine. Even though the data is disconnected, you want the ability to keep the data (with all of its tables and relations in place) on the client side. ADO.NET is a reflection of the data store itself, with tables, columns, rows, and relations all in place. When completed working on the client side copy of the data, the changes done to the data could be made persistent back into the data store from where the data was retrieved. The technology that enables the user or the programmer to perform this task is the DataSet. Like their counterparts in the unmanaged world, managed applications can and often do utilize industrial-strength databases such as Microsoft SQL Server and Oracle 8i. Thats why Microsoft created ADO.NET, an elegant, easy-to-use database API for managed applications. ADO.NET is exposed
Sikkim Manipal University Page No. 205

DOT Net Technologies

Unit 7

as a set of classes in the .NET Framework class librarys System.Data namespace and its descendants. Unlike ADO and OLE DB, its immediate predecessors, ADO.NET was designed from the outset to work in the connectionless world of the Web. It also integrates effortlessly with XML, bridging the gap between relational data and XML and simplifying the task of moving back and forth between them. If youre like most developers, you believe that the last thing the world needs is another database access API. Why, when we already have ODBC, DAO, ADO, RDO, OLE DB, and others, do we need yet another API? The short answer is that the world has changed, and none of the existing data access technologies maps very well to a world that revolves around that stateless, text-based protocol called HTTP. In addition, managed applications need an efficient and intuitive way to talk to databases. Thats ADO.NET in a nutshellthe database language spoken by managed applications. ADO.NET is an essential component of the .NET Framework. Lets see how it works. ADO.NET looks very similar to ADO, its predecessor. The key difference is that ADO.NET is a disconnected data architecture. What is Disconnected Architecture? In this architecture, data is retrieved from a database and cached on your local machine. You manipulate the data on your local computer and connect to the database only when you wish to alter records or acquire new data. Advantage of Disconnected Architecture: The biggest advantage with this architecture is that you avoid many of the problems associated with connected data objects that do not scale very well. Database connections are resource-intensive, and it is difficult to have thousands (or hundreds of thousands) of simultaneous continuous connections. A disconnected architecture is resource-frugal.
Sikkim Manipal University Page No. 206

DOT Net Technologies

Unit 7

ADO.NET connects to the database to retrieve data, and connects again to update data when you've made changes. Most applications spend most of their time simply reading through data and displaying it; ADO.NET provides a disconnected subset of the data for your use while reading and displaying. Disconnected data objects work in a mode similar to that of the Web. All web sessions are disconnected, and state is not preserved between web pages. ADO.NET separates data access from data manipulation into discrete components that can be used separately or in tandem. ADO.NET includes .NET Framework data providers for connecting to a database, executing commands, and retrieving results. Those results are either processed directly, placed in an ADO.NET DataSet object in order to be exposed to the user in an ad hoc manner, combined with data from multiple sources, or passed between tiers. The DataSet object can also be used independently of a .NET Framework data provider to manage data local to the application or sourced from XML. The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes found in System.Xml.dll. .Net Data Providers A .NET Framework data provider is used for connecting to a database, executing commands, and retrieving results. Those results are either processed directly, placed in a DataSet in order to be exposed to the user as needed, combined with data from multiple sources, or remoted between tiers. .NET Framework data providers are lightweight, creating a minimal layer between the data source and code, increasing performance without sacrificing functionality.

Sikkim Manipal University

Page No. 207

DOT Net Technologies

Unit 7

The following table lists the data providers that are included in the .NET Framework.
.NET Framework data provider .NET Framework Data Provider for SQL Server .NET Framework Data Provider for OLE DB .NET Framework Data Provider for ODBC .NET Framework Data Provider for Oracle Description Provides data access for Microsoft SQL Server version 7.0 or later versions. Uses the System.Data.SqlClient namespace. For data sources exposed by using OLE DB. Uses the System.Data.OleDb namespace. For data sources exposed by using ODBC. Uses the System.Data.Odbc namespace. For Oracle data sources. The .NET Framework Data Provider for Oracle supports Oracle client software version 8.1.7 and later, and uses the System.Data.OracleClient namespace.

Core Objects of .NET Framework Data Providers The following table outlines the four core objects that make up a .NET Framework data provider.
Object Connection Command Description Establishes a connection to a specific data source. The base class for all Connection objects is the DbConnection class. Executes a command against a data source. Exposes Parameters and can execute in the scope of a Transaction from a Connection. The base class for all Command objects is the DbCommand class. Reads a forward-only, read-only stream of data from a data source. The base class for all DataReader objects is the DbDataReader class. Populates a DataSet and resolves updates with the data source. The base class for all DataAdapter objects is the DbDataAdapter class.

DataReader

DataAdapter

Sikkim Manipal University

Page No. 208

DOT Net Technologies

Unit 7

In addition to the core classes listed in the table earlier in this document, a .NET Framework data provider also contains the classes listed in the following table.
Object Transaction Description Enlists commands in transactions at the data source. The base class for all Transaction objects is the DbTransaction class. ADO.NET also provides support for transactions using classes in the System.Transactions namespace. A helper object that automatically generates command properties of a DataAdapter or derives parameter information from a stored procedure and populates the Parameters collection of a Command object. The base class for all CommandBuilder objects is the DbCommandBuilder class. A helper object that provides a simple way to create and manage the contents of connection strings used by the Connection objects. The base class for all ConnectionStringBuilder objects is the DbConnectionStringBuilder class. Defines input, output, and return value parameters for commands and stored procedures. The base class for all Parameter objects is the DbParameter class. Returned when an error is encountered at the data source. For an error encountered at the client, .NET Framework data providers throw a .NET Framework exception. The base class for all Exception objects is the DbException class. Exposes the information from a warning or error returned by a data source. Provided for .NET Framework data provider code access security attributes. The base class for all ClientPermission objects is the DBData Permission class.

CommandBuilder

ConnectionStringBuilder

Parameter

Exception

Error ClientPermission

The .NET Framework Data Provider for SQL Server The .NET Framework Data Provider for SQL Server uses its own protocol to communicate with SQL Server. It is lightweight and performs well because it
Sikkim Manipal University Page No. 209

DOT Net Technologies

Unit 7

is optimized to access a SQL Server directly without adding an OLE DB or Open Database Connectivity (ODBC) layer. The following illustration contrasts the .NET Framework Data Provider for SQL Server with the .NET Framework Data Provider for OLE DB. The .NET Framework Data Provider for OLE DB communicates to an OLE DB data source through both the OLE DB Service component, which provides connection pooling and transaction services, and the OLE DB provider for the data source. Note: The .NET Framework Data Provider for ODBC has a similar architecture to the .NET Framework Data Provider for OLE DB; for example, it calls into an ODBC Service Component. The .NET Framework Data Provider for SQL Server uses its own protocol to communicate with SQL Server. It is lightweight and performs well because it is optimized to access a SQL Server directly without adding an OLE DB or Open Database Connectivity (ODBC) layer. The following illustration contrasts the .NET Framework Data Provider for SQL Server with the .NET Framework Data Provider for OLE DB. The .NET Framework Data Provider for OLE DB communicates to an OLE DB Data source through both the OLE DB Service component, which provides connection pooling and transaction services, and the OLE DB provider for the data source. Note: The .NET Framework Data Provider for ODBC has a similar architecture to the .NET Framework Data Provider for OLE DB; for example, it calls into an ODBC Service Component. To use the .NET Framework Data Provider for SQL Server, you must have access to SQL Server 7.0 or later versions. The.NET Framework Data Provider for SQL Server classes are located in the System. Data.SqlClient namespace. For earlier versions of SQL Server, use the .NET Framework Data Provider for OLE DB with the SQL Server OLE DB provider System. Data.OleDb.
Sikkim Manipal University Page No. 210

DOT Net Technologies

Unit 7

The .NET Framework Data Provider for SQL Server supports both local and distributed transactions. For distributed transactions, the .NET Framework Data Provider for SQL Server, by default, automatically enlists in a transaction and obtains transaction details from Windows Component Services or System.Transactions. The following code example shows how to include the

System.Data.SqlClient namespace in your applications. using System.Data.SqlClient; The .NET Framework Data Provider for OLE DB The .NET Framework Data Provider for OLE DB uses native OLE DB through COM interoperability to enable Data access. The .NET Framework Data Provider for OLE DB supports both local and distributed transactions. For distributed transactions, the .NET Framework Data Provider for OLE DB, by default, automatically enlists in a transaction and obtains transaction details from Windows 2000 Component Services. The following table shows the providers that have been tested with ADO.NET.
Driver SQLOLEDB MSDAORA Microsoft.Jet.OLEDB.4.0 Provider Microsoft OLE DB provider for SQL Server Microsoft OLE DB provider for Oracle OLE DB provider for Microsoft Jet

The.NET Framework Data Provider for OLE DB does not support OLE DB version 2.5 interfaces. OLE DB Providers that require support for OLE DB 2.5 interfaces will not function correctly with the .NET Framework Data Provider for OLE DB. This includes the Microsoft OLE DB provider for Exchange and the Microsoft OLE DB provider for Internet Publishing.

Sikkim Manipal University

Page No. 211

DOT Net Technologies

Unit 7

The .NET Framework Data Provider for OLE DB does not work with the OLE DB provider for ODBC (MSDASQL). To access an ODBC data source using ADO.NET, use the .NET Framework Data Provider for ODBC. .NET Framework Data Provider for OLE DB classes are located in the System. Data.OleDb namespace. The following code example shows how to include the System.Data.OleDb namespace in your applications. C# Code using System.Data.OleDb;

The .NET Framework Data Provider for ODBC The .NET Framework Data Provider for ODBC uses the native ODBC Driver Manager (DM) to enable data access. The ODBC data provider supports both local and distributed transactions. For distributed transactions, the ODBC data provider, by default, automatically enlists in a transaction and obtains transaction details from Windows 2000 Component Services. The following table shows the ODBC drivers tested with ADO.NET.
Driver SQL Server Microsoft ODBC for Oracle Microsoft Access Driver (*.mdb)

.NET Framework Data Provider for ODBC classes are located in the System.Data.Odbc namespace. The following code example shows how to include the System.Data.Odbc namespace in your applications. C# Code using System.Data.Odbc;

Sikkim Manipal University

Page No. 212

DOT Net Technologies

Unit 7

The .NET Framework Data Provider for Oracle The .NET Framework Data Provider for Oracle enables data access to Oracle data sources through Oracle client connectivity software. The data provider supports Oracle client software version 8.1.7 or a later version. The data provider supports both local and distributed transactions. The .NET Framework Data Provider for Oracle requires Oracle client software (version 8.1.7 or a later version) on the system before you can connect to an Oracle data source. .NET Framework Data Provider for Oracle classes are located in the System.Data.OracleClient namespace and are contained in the System.Data.OracleClient.dll assembly. You must reference both the System.Data.dll and the System.Data.OracleClient.dll when you compile an application that uses the data provider. The following code example shows how to include the

System.Data.OracleClient namespace in your applications. C# Code using System.Data; using System.Data.OracleClient;

Choosing a .NET Framework Data Provider Depending on the design and data source for your application, your choice of .NET Framework data provider can improve the performance, capability, and integrity of your application. The following table discusses the advantages and limitations of each .NET Framework data provider.

Sikkim Manipal University

Page No. 213

DOT Net Technologies

Unit 7

Provider .NET Framework Data Provider for SQL Server

Notes Recommended for middle-tier applications that use Microsoft SQL Server 7.0 or a later version. Recommended for single-tier applications that use Microsoft Database Engine (MSDE) or SQL Server 7.0 or a later version. Recommended over use of the OLE DB provider for SQL Server (SQLOLEDB) with the .NET Framework Data Provider for OLE DB. For SQL Server 6.5 and earlier, you must use the OLE DB provider for SQL Server with the .NET Framework Data Provider for OLE DB. Recommended for middle-tier applications that use SQL Server 6.5 or earlier. For SQL Server 7.0 or a later version, the .NET Framework Data Provider for SQL Server is recommended. Also recommended for single-tier applications that use Microsoft Access databases. Use of an Access database for a middle-tier application is not recommended. Recommended for middle and single-tier applications that use ODBC data sources. Recommended for middle and single-tier applications that use Oracle data sources.

.NET Framework Data Provider for OLE DB

.NET Framework Data Provider for ODBC .NET Framework Data Provider for Oracle

Objectives This unit provides with an overview of the features of ADO.NET. At the end of this unit the reader would be able to: Understand the concepts of database development using ADO.NET Describe various ways to connect to different data sources using built in features of ADO.NET Understand the usage of strings and stringbuilders in ADO.NET Describe the concepts of namespaces and classes The Usage of DataAdapters in fetching the data from a source Describe the usage of XML data in ADO.NET
Page No. 214

Sikkim Manipal University

DOT Net Technologies

Unit 7

7.2 Connecting to a Data Source using ADO.NET


In ADO.NET you use a Connection object to connect to a specific data source by supplying necessary authentication information in a connection string. The Connection object you use depends on the type of data source. Each .NET Framework data provider included with the .NET Framework has a Connection object: the .NET Framework Data Provider for OLE DB includes an OleDbConnection object, the .NET Framework Data Provider for SQL Server includes a SqlConnection object, the .NET Framework Data Provider for ODBC includes an OdbcConnection object, and the .NET Framework Data Provider for Oracle includes an OracleConnection object. To connect to Microsoft SQL Server 7.0 or later, use the SqlConnection object of the .NET Framework Data Provider for SQL Server. To connect to an OLE DB data source, or to Microsoft SQL Server 6.x or earlier, use the OleDbConnection object of the .NET Framework Data Provider for OLE DB. To connect to an ODBC data source, use the OdbcConnection object of the .NET Framework Data Provider for ODBC. To connect to an Oracle data source, use the OracleConnection object of the .NET Framework Data Provider for Oracle. Closing Connections We recommend that you always close the connection when you are finished using it, so that the connection can be returned to the pool. The Using block in Visual Basic or C# automatically disposes of the connection when the code exits the block, even in the case of an unhandled exception. You can also use the Close or Dispose methods of the connection object for the provider that you are using. Connections that are not explicitly closed might not be added or returned to the pool. For example, a connection that has gone out of scope but that has not been explicitly closed will only be

Sikkim Manipal University

Page No. 215

DOT Net Technologies

Unit 7

returned to the connection pool if the maximum pool size has been reached and the connection is still valid. Note: 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. Connecting to SQL Server The .NET Framework Data Provider for SQL Server supports a connection string format that is similar to the OLE DB (ADO) connection string format. For valid string format names and values, see the ConnectionString property of the SqlConnection object. You can also use the

SqlConnectionStringBuilder class to create syntactically valid connection strings at run time. The following code example demonstrates how to create and open a connection to a SQL Server 7.0 or later database.
C# Code // Assumes connectionString is a valid connection string. using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // Do work here. }

Connecting to an OLE DB Data Source The .NET Framework Data Provider for OLE DB provides connectivity to data sources exposed using OLE DB and to Microsoft SQL Server 6.x or
Sikkim Manipal University Page No. 216

DOT Net Technologies

Unit 7

earlier (through SQLOLEDB, the OLE DB Provider for SQL Server), using the OleDbConnection object. For the .NET Framework Data Provider for OLE DB, the connection string format is identical to the connection string format used in ADO, with the following exceptions: The Provider keyword is required. The URL, Remote Provider, and Remote Server keywords are not supported. The following code example demonstrates how to create and open a connection to an OLE DB data source. C# Code // Assumes connectionString is a valid connection string. using (OleDbConnection connection = new OleDbConnection(connectionString)) { connection.Open(); // Do work here. }

Connecting to an ODBC Data Source The .NET Framework Data Provider for ODBC provides connectivity to data sources exposed using ODBC using the OdbcConnection object. For the .NET Framework Data Provider for ODBC, the connection string format is designed to match the ODBC connection string format as closely as possible. You may also supply an ODBC data source name (DSN). The following code example demonstrates how to create and open a connection to an ODBC data source.

Sikkim Manipal University

Page No. 217

DOT Net Technologies

Unit 7

C# Code // Assumes connectionString is a valid connection string. using (OdbcConnection connection = new OdbcConnection(connectionString)) { connection.Open(); // Do work here. }

Connecting to an Oracle Data Source The .NET Framework Data Provider for Oracle provides connectivity to Oracle data sources using the OracleConnection object. For the .NET Framework Data Provider for Oracle, the connection string format is designed to match the OLE DB Provider for Oracle (MSDAORA) connection string format as closely as possible. The following code example demonstrates how to create and open a connection to an Oracle data source. C# Code // Assumes connectionString is a valid connection string. using (OracleConnection connection = new OracleConnection(connectionString)) { connection.Open(); // Do work here. } OracleConnection nwindConn = new OracleConnection("Data

Source=MyOracleServer;Integrated Security=yes;"); nwindConn.Open();

Sikkim Manipal University

Page No. 218

DOT Net Technologies

Unit 7

7.3 Connection Strings using ADO.NET


The .NET Framework 2.0 provides new capabilities for working with connection strings, including the introduction of new keywords to the connection string builder classes, which facilitate creating valid connection strings at run time. A connection string contains initialization information that is passed as a parameter from a data provider to a data source. The syntax depends on the data provider, and the connection string is parsed during the attempt to open a connection. Syntax errors generate a run-time exception, but other errors occur only after the data source receives connection information. Once validated, the data source applies the options specified in the connection string and opens the connection. The format of a connection string is a semicolon-delimited list of key/value parameter pairs: keyword1=value; keyword2=value; Keywords are not case sensitive, and spaces between key/value pairs are ignored. However, values may be case sensitive, depending on the data source. Any values containing a semicolon, single quotation marks, or double quotation marks must be enclosed in double quotation marks. Valid connection string syntax depends on the provider, and has evolved over the years from earlier APIs like ODBC. The .NET Framework Data Provider for SQL Server incorporates many elements from older syntax and is generally more flexible with common connection string syntax. There are frequently equally valid synonyms for connection string syntax elements, but some syntax and spelling errors can cause problems. For example, "Integrated Security=true" is valid, whereas "IntegratedSecurity=true" causes an error. In addition, connection strings constructed at run time from

Sikkim Manipal University

Page No. 219

DOT Net Technologies

Unit 7

unvalidated user input can lead to string injection attacks, jeopardizing security at the data source. To address these problems, ADO.NET 2.0 introduces new connection string builders for each .NET Framework data provider. Keywords are exposed as properties, enabling connection string syntax to be validated before submission to the data source. There are also new classes that simplify storing and retrieving connection strings in configuration files and encrypting them using protected configuration.

7.4 Connection String Builders (ADO.NET)


In previous versions of ADO.NET, compile-time checking of connection strings with concatenated string values did not occur, so at run time, an incorrect keyword would generate an ArgumentException. Each of the .NET Framework data providers supports different syntax for connection string keywords, making constructing valid connection strings difficult if done manually. To address this problem, ADO.NET 2.0 introduces new connection string builders for each .NET Framework data provider. Each data provider provides a strongly typed connection string builder class that inherits from DbConnectionStringBuilder. The following table lists the .NET Framework data providers and their associated connection string builder classes.
Provider System.Data.SqlClient System.Data.OleDb System.Data.Odbc System.Data.OracleClient ConnectionStringBuilder class SqlConnectionStringBuilder OleDbConnectionStringBuilder OdbcConnectionStringBuilder OracleConnectionStringBuilder

Sikkim Manipal University

Page No. 220

DOT Net Technologies

Unit 7

7.5 Building Connection Strings from Configuration Files


If certain elements of a connection string are known ahead of time, they can be stored in a configuration file and retrieved at run time to construct a complete connection string. For example, the name of the database might be known in advance, but not the name of the server. Or you might want a user to supply a name and password at run time without being able to inject other values into the connection string. One of the overloaded constructors for a connection string builder takes a String as an argument, which allows you to supply a partial connection string which can then be completed from user input. The partial connection string can be stored in a configuration file and retrieved at run time. Example This example demonstrates retrieving a partial connection string from a configuration file and completing it by setting the DataSource, UserID, and Password properties of the SqlConnectionStringBuilder. The configuration file is defined as follows. <connectionStrings> <clear/> <add name="partialConnectString" connectionString="Initial Catalog=Northwind;" providerName="System.Data.SqlClient" /> </connectionStrings>

Note: You must set a reference to the System.Configuration.dll in your project in order for the code to run.

Sikkim Manipal University

Page No. 221

DOT Net Technologies

Unit 7

private static void BuildConnectionString(string dataSource, string userName, string userPassword) { // Retrieve the partial connection string named databaseConnection // from the application's app.config or web.config file. ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["partialConnectString"]; if (null != settings) { // Retrieve the partial connection string. string connectString = settings.ConnectionString; Console.WriteLine("Original: {0}", connectString); // Create a new SqlConnectionStringBuilder based on the // partial connection string retrieved from the config file. SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);

// Supply the additional values. builder.DataSource = dataSource; builder.UserID = userName; builder.Password = userPassword; Console.WriteLine("Modified: {0}"builder.ConnectionString); } }

7.6 Basic ADO.NET Features


The following examples make use of Northwind.mdf SQL Server Express Database File. To get this database, search for Northwind and pubs sample databases for SQL Server 2000. Selecting Data After the connection to the data source is open and ready to use, u probably want to read the data from the data source. If you do not want to manipulate the data, but simply to read it or transfer it from one spot to another, you use the DataReader class.
Sikkim Manipal University Page No. 222

DOT Net Technologies

Unit 7

In the following example, you use the GetCompanyData() function to provide a list of company names from the SQL Northwind database.

List<string> returnData = new List<string>(); myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); while(myReader.Read()) { returnData.Add(myReader[CompanyName].ToString()); } return returnData; } }

In this example, you create an instance of both the SqlConnection and the SqlCommand classes. Then, before you open the connection, you simply pass the SqlCommand class a SQL command selecting specific data from the Northwind Database. After your connection is opened you create a DataReader. To read the data from the database, you iterate through the data with the DataReader by using the myReader.Read() method. After the List object is built, the connection is closed, and the object is returned from the function.
Sikkim Manipal University Page No. 223

DOT Net Technologies

Unit 7

Data Insertion This data may have been passed to you by the end user through the XML Web Service, or it may be data that you generated within the logic of your class.

Insertion of specific values into specific columns is done using the SQL command string. The actual insertion is initiated using the

cmd.ExecuteNonQuery() command. This executes a command on the data when you do not want anything in return. Data Updation Updation is the process of performing operations on existing rows of data in a table. In the following example, we update an employee by putting a value in the emp_bonus column if the employee has been at the company for a time period of minimum 5 years or more.

Sikkim Manipal University

Page No. 224

DOT Net Technologies

Unit 7

The update function iterates through all the employees in the table and changes the value of the emp_bonus field to 1000 if an employee has been within the company for more than five years. Deletion of Data This operation deletes the data from the data source specified. This operation is done using the SQL command string and the method ExecuteNonQuery(). An example code for performing this operation is shown below:

Sikkim Manipal University

Page No. 225

DOT Net Technologies

Unit 7

We assign the ExecuteNonQuery() command to an integer variable to return the number of records deleted after execution.

7.7 ADO.NET Namespaces and Classes


There are six core ADO.NET namespaces. In addition to these namespaces, each new data provider can have its own namespace. For example, the Oracle.NET data provider adds a namespace of System.Data.OracleClient (A Microsoft built Oracle Data Provider).
Namespace System.Data Description This is the core namespace of ADO.NET. It contains classes used by all data providers. It contains classes to represent tables, columns, rows, and the DataSet class. It also contains some useful interfaces such as IDbCommand, IDbConnection, and IDbDataAdapter. These interfaces are used by all managed providers, enabling them to plug into the core of ADO.NET. It defines the common classes used as base classes for data providers. All data providers share theses classes. Example: DbConnection and DbDataAdapter. It defines classes that work with OLE-DB data sources using the .NET OleDb data provider. It contains classes such as OleDbConnection and OleDbCommand. It define classes that work with ODBC data sources using the .NET ODBC data provider. It contains classes such as OdbcConnection and OdbcCommand It defines a data provider for SQL server 7.0 or higher databases. It contains classes such as SqlConnection and SqlCommand. It defines a few classes that represent specific data types for the SQL Server database.

System.Data.Common

System.Data.OleDb

System.Data.Odbc

System.Data.SqlClient

System.Data.SqlTypes

Sikkim Manipal University

Page No. 226

DOT Net Technologies

Unit 7

ADO.NET has the following three distinct types of classes: 1. Disconnected Classes: These classes provide the basic structure for ADO.NET framework. Example: DataTable class. The objects of this class are capable of storing data without any dependency on a specific data provider. 2. Shared Classes: They form the base classes for data providers and are shared commonly among all the data providers. 3. Data Provider Classes: They are meant to work with different kinds of data sources. They are used to perform all data-management operations on specific databases. For example, the SqlClient data provider works only with SQL server database. A Data Provider contains the following objects: 1. Connection 2. Command 3. DataReader The following are the basic steps in creation and execution of database query operations in ADO.NET: Step-1: First create the Connection object and provide it with necessary information such as the connection string. Step-2: Create a command object and provide it with the details of the SQL command that is to be executed. Step-3: Decide whether the command returns a result set. If the command does not return a result set, you can simply execute the command by calling one of its several Execute methods. If the command returns a result set, you must make a decision about whether you want to retain the result set for future use without maintaining the connection to the database. If you want to retain the result set, you must
Sikkim Manipal University Page No. 227

DOT Net Technologies

Unit 7

create a DataAdapter and use it to fill a Database object and use it to fill a DataSet or a DataTable object. These objects are capable of maintaining their information in a disconnected mode. If you do not want to retain the result set, but rather simply process the command, you can use the Command object to create a DataReader object. The DataReader object needs a live connection to the database, and it works as a forward-only, read-only cursor. Connection Object It creates a link (or connection) to a specified data source. This object must contain the necessary information to discover the specified data source and to log in to it properly using a defined user name and password combination. This information is provided via a single string called Connection String. The data provider for working with a SQL data store includes a SqlConnection class that performs the connection operation. The

SqlConnection object is a class that is specific to the SqlClient provider. The properties for the SqlConnection class are shown in the following table:
Property ConnectionString Database DataSource Description This property allows you to read or provide the connection string that should be used by the SqlConnection Object A read-only property that returns the name of the database to use after the connection is opened A read-only property that returns the name of the instance of the SQL Server database used by the SqlConnection object A read-only property that returns the current state of the connection. The possible values are Broken, Closed, Connecting, Executing, Fetching, and Open.

State

Sikkim Manipal University

Page No. 228

DOT Net Technologies

Unit 7

Figure: Connection to a SQL Database

To make this connection work, make sure that proper namespaces are imported before you start using any of the classes that work with SQL. The first step in making a connection is to create an instance of the SqlConnection class and assign it to the con instance. The SqlConnection class is initialized after you pass in the connection string as a parameter to the class. The second way of making a connection is to put the connection string within the applications web.config file and then to make a reference to the web.config file. To define the connection string within the web.config file, you are going to make use of the <connectionString> section. From this section, you can place an <add> element within it to define your connection. Figure: Coding the Connection String within the web.config file

Sikkim Manipal University

Page No. 229

DOT Net Technologies

Unit 7

Now that you have a connection string within the web.config file, you can then make use of that connection string directly in your code by using the ConnectionManager object as shown in the listing below:

For this line of code to work, we have to make a reference to the System.Configuration namespace. When you complete your connection to the data source, be sure that you explicitly close the connection by using con.close(). The .NET framework does not implicitly release the connections when they fall out of scope.

7.8 Fetching the data: DataAdapter


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 DataAdapter object: the .NET Framework Data Provider for OLE DB includes an OleDbDataAdapter object, the .NET Framework Data Provider for SQL Server includes a SqlDataAdapter object, the .NET Framework Data Provider for ODBC includes an OdbcDataAdapter object, and the .NET Framework Data Provider for Oracle includes an OracleDataAdapter object. DataAdapter Members Represents a set of SQL commands and a database connection that are used to fill the DataSet and update the data source.
Sikkim Manipal University Page No. 230

DOT Net Technologies

Unit 7

The DataAdapter type exposes the following members. Constructors


Name DataAdapter Description Overloaded. Initializes a new instance of a DataAdapter class

Methods
Name CloneInternals CreateObjRef Description Obsolete. Creates a copy of this instance of DataAdapter. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) Creates a new DataTableMappingCollection. Overloaded. Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Overloaded. Adds or refreshes rows in the DataSet to match those in the data source. Overloaded. Adds a DataTable to the specified DataSet. Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.) Gets the parameters set by the user when executing an SQL SELECT statement. Serves as a hash function for a particular type. (Inherited from Object.) Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.) Gets the Type of the current instance. (Inherited from Object.) Indicates whether a DataTableMappingCollection has been created.

CreateTableMappings Dispose Equals Fill FillSchema Finalize

GetFillParameters GetHashCode GetLifetimeService

GetService

GetType HasTableMappings

Sikkim Manipal University

Page No. 231

DOT Net Technologies

Unit 7

InitializeLifetimeService

Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.) Overloaded. Invoked when an error occurs during a Fill. Resets FillLoadOption to its default state and causes DataAdapter.Fill to honor AcceptChangesDuringFill. Determines whether the AcceptChanges DuringFill property should be persisted. Determines whether the property should be persisted. FillLoadOption

MemberwiseClone OnFillError ResetFillLoadOption

ShouldSerializeAcceptChangesDuringFill ShouldSerializeFillLoadOption ShouldSerializeTableMappings

Determines whether one or more Data TableMapping objects exist and they should be persisted. Returns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.) In .NET Compact Framework 3.5, this member is inherited from Object.ToString(). In XNA Framework 1.0, this member is inherited from Object.ToString(). Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified DataSet from a DataTable named "Table."

ToString

Update

Properties
Name AcceptChangesDuringFill Description Gets or sets a value indicating whether AcceptChanges is called on a DataRow after it is added to the DataTable during any of the Fill operations. Gets or sets whether AcceptChanges is called during a Update. Gets a value indicating whether the component can raise an event. (Inherited from Component.) Gets the IContainer that contains the Component. (Inherited from Component.) Gets or sets a value that specifies whether to generate an exception when an error is encountered during a row update.

AcceptChangesDuringUpdate CanRaiseEvents

Container ContinueUpdateOnError

Sikkim Manipal University

Page No. 232

DOT Net Technologies

Unit 7

DesignMode

Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.) Gets the list of event handlers that are attached to this Component. (Inherited from Component.) Gets or sets the LoadOption that determines how the adapter fills the DataTable from the DbDataReader. Determines the action to take when incoming data does not have a matching table or column. Determines the action to take when existing DataSet schema does not match incoming data. Gets or sets whether the Fill method should return provider-specific values or common CLS-compliant values. Gets or sets the ISite of the Component. (Inherited from Component.) Gets a collection that provides the master mapping between a source table and a DataTable.

Events

FillLoadOption

MissingMappingAction

MissingSchemaAction

ReturnProviderSpecificTypes

Site TableMappings

Events
Name Disposed FillError Description Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.) Returned when an error occurs during a fill operation.

The Common Behavior: IDbConnection Represents an open connection to a data source, and is implemented by .NET Framework data providers that access relational databases. Namespace: System.Data Assembly: System.Data (in System.Data.dll) Syntax: In C# public interface IDbConnection: IDisposable
Sikkim Manipal University Page No. 233

DOT Net Technologies

Unit 7

The IDbConnection interface enables an inheriting class to implement a Connection class, which represents a unique session with a data source (for example, a network connection to a server). For more information about Connection classes, see Connecting to a Data Source (ADO.NET). An application does not create an instance of the IDbConnection interface directly, but creates an instance of a class that inherits IDbConnection. Classes that inherit IDbConnection must implement all inherited members, and typically define additional members to add provider-specific

functionality. For example, the IDbConnection interface defines the ConnectionTimeout property. In turn, the SqlConnection class inherits this property, and also defines the PacketSize property. Notes to Implementers: To promote consistency among .NET Framework data providers, name the inheriting class in the form PrvClassname where Prv is the uniform prefix given to all classes in a specific .NET Framework data provider namespace. For example, Sql is the prefix of the SqlConnection class in the System.Data.SqlClient namespace. When you inherit from the IDbConnection interface, you should implement the following constructors:
Item PrvConnection() PrvConnection(string connectionString) Description Initializes a new instance of the PrvConnection class. Initializes a new instance of the PrvConnection class when given a string containing the connection string.

Examples The following example creates instances of the derived classes, SqlCommand and SqlConnection. The SqlConnection is opened and set as the Connection for the SqlCommand. The example then calls

ExecuteNonQuery, and closes the connection. To accomplish this, the


Sikkim Manipal University Page No. 234

DOT Net Technologies

Unit 7

ExecuteNonQuery is passed a connection string and a query string that is a Transact-SQL INSERT statement.

IDbConnection Members Represents an open connection to a data source, and is implemented by .NET Framework data providers that access relational databases. The IDbConnection type exposes the following members. Methods
Name BeginTransaction ChangeDatabase Close CreateCommand Dispose Description Overloaded. Begins a database transaction. Changes the current Connection object. database for an open

Closes the connection to the database. Creates and returns a Command object associated with the connection. Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. (Inherited from IDisposable.) Opens a database connection with the settings specified by the ConnectionString property of the provider-specific Connection object.

Open

Sikkim Manipal University

Page No. 235

DOT Net Technologies

Unit 7

Properties
Name ConnectionString ConnectionTimeout Description Gets or sets the string used to open a database. Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error. Gets the name of the current database or the database to be used after a connection is opened. Gets the current state of the connection.

Database State

The Common Logic: DbConnection The DbConnection Class Represents a connection to a database. Namespace: System.Data.Common Assembly: System.Data (in System.Data.dll) Syntax:

DbConnection Members The DbConnection type exposes the following members. Constructors
Name DbConnection Description Initializes a new instance of the DbConnection class.

Sikkim Manipal University

Page No. 236

DOT Net Technologies

Unit 7

Methods
Name BeginDbTransaction BeginTransaction ChangeDatabase Close CreateCommand CreateDbCommand CreateObjRef Description Starts a database transaction. Overloaded. Starts a database transaction. Changes the connection. current database for an open

Closes the connection to the database. This is the preferred method of closing any open connection. Creates and returns a DbCommand associated with the current connection. Creates and returns a DbCommand associated with the current connection. object object

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) Overloaded. Enlists in the specified transaction. Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.) Serves as a hash function for a particular type. (Inherited from Object.) Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) Overloaded. Returns schema information for the data source of this DbConnection. Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.) Gets the Type of the current instance. (Inherited from Object.) Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.) Overloaded. Page No. 237

Dispose EnlistTransaction Equals Finalize

GetHashCode GetLifetimeService

GetSchema GetService

GetType InitializeLifetimeService

MemberwiseClone Sikkim Manipal University

DOT Net Technologies

Unit 7

OnStateChange Open ToString

Raises the StateChange event. Opens a database connection with the settings specified by the ConnectionString. Returns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.) In .NET Compact Framework 3.5, this member is inherited from Object.ToString(). In XNA Framework 1.0, this member is inherited from Object.ToString().

Properties
Name CanRaiseEvents ConnectionString ConnectionTimeout Container Database Description Gets a value indicating whether the component can raise an event. (Inherited from Component.) Gets or sets the string used to open the connection. Gets the time to wait while establishing a connection before terminating the attempt and generating an error. Gets the IContainer that contains the Component. (Inherited from Component.) Gets the name of the current database after a connection is opened, or the database name specified in the connection string before the connection is opened. Gets the name of the database server to which to connect. Gets the DbProviderFactory for this DbConnection. Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.) Gets the list of event handlers that are attached to this Component. (Inherited from Component.) Gets a string that represents the version of the server to which the object is connected. Gets or sets the ISite of the Component. (Inherited from Component.) Gets a string that describes the state of the connection.

DataSource DbProviderFactory DesignMode Events ServerVersion Site State

Sikkim Manipal University

Page No. 238

DOT Net Technologies

Unit 7

Events
Name Disposed StateChange Description Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.) Occurs when the state of the event changes.

Explicit Interface Implementations


Name IDbConnection.BeginTransaction Description Begins a database transaction. 1. BeginTransaction():Begins a database transaction. 2. BeginTransaction(IsolationLevel): Begins a database transaction with the specified IsolationLevel value.

IDbConnection.BeginTransaction IDbConnection.CreateCommand

Connection Pooling Connection pooling enables an application to use a connection from a pool of connections that do not need to be reestablished for each use. Once a connection has been created and placed in a pool, an application can reuse that connection without performing the complete connection process. Using a pooled connection can result in significant performance gains, because applications can save the overhead involved in making a connection. This can be particularly significant for middle-tier applications that connect over a network or for applications that repeatedly connect and disconnect, such as Internet applications. In addition to performance gains, the connection pooling architecture enables an environment and its associated connections to be used by multiple components in a single process. This means that stand-alone components in the same process can interact with each other without being aware of each other. A connection in a connection pool can be used repeatedly by multiple components.
Sikkim Manipal University Page No. 239

DOT Net Technologies

Unit 7

Note: Connection pooling can be used by an ODBC application exhibiting ODBC 2.x behavior, as long as the application can call SQLSetEnvAttr. When using connection pooling, the application must not execute SQL statements that change the database or the context of the database, such as changing the <database name>, which changes the catalog used by a data source. An ODBC driver must be fully thread-safe, and connections must not have thread affinity to support connection pooling. This means the driver is able to handle a call on any thread at any time and is able to connect on one thread, to use the connection on another thread, and to disconnect on a third thread. The connection pool is maintained by the Driver Manager. Connections are drawn from the pool when the application calls SQLConnect or SQLDriverConnect and are returned to the pool when the application calls SQLDisconnect. The size of the pool grows dynamically, based on the requested resource allocations. It shrinks based on the inactivity timeout: If a connection is inactive for a period of time (it has not been used in a connection), it is removed from the pool. The size of the pool is limited only by memory constraints and limits on the server. The Driver Manager determines whether a specific connection in a pool should be used according to the arguments passed in SQLConnect or SQLDriverConnect, and according to the connection attributes set after the connection was allocated. When the Driver Manager is pooling connections, it needs to be able to determine if a connection is still working before handing out the connection. Otherwise, the Driver Manager keeps on handing out the dead connection to the application whenever a transient network failure occurs. A new connection attribute has been defined in ODBC 3.x: SQL_ATTR_CONNECTION_DEAD. This is a read-only connection attribute that returns either SQL_CD_TRUE or SQL_CD_FALSE. The value
Sikkim Manipal University Page No. 240

DOT Net Technologies

Unit 7

SQL_CD_TRUE means that the connection has been lost, while the value SQL_CD_FALSE means that the connection is still active. (Drivers conforming to earlier versions of ODBC can also support this attribute.) A driver must implement this option efficiently or it will impair the connection pooling performance. Specifically, a call to get this connection attribute should not cause a round trip to the server. Instead, a driver should just return the last known state of the connection. The connection is dead if the last trip to the server failed, and not dead if the last trip succeeded. In order to prevent unwanted repeated attempts by the Driver Manager to reestablish a connection when connection pooling is enabled, you can set ODBCGetTryWaitValue. ODBCSetTryWaitValue saves the information in the registry at the following location: HKEY_LOCAL_MACHINE\Software\Odbc\Odbcinst.ini\ODBC Connection Pooling\Retry Wait

7.9 XML & ADO.NET


With ADO.NET you can fill a DataSet from an XML stream or document. You can use the XML stream or document to supply to the DataSet either data, schema information, or both. The information supplied from the XML stream or document can be combined with existing data or schema information already present in the DataSet. ADO.NET also allows you to create an XML representation of a DataSet, with or without its schema, in order to transport the DataSet across HTTP for use by another application or XML-enabled platform. In an XML representation of a DataSet, the data is written in XML and the schema, if it is included inline in the representation, is written using the XML Schema definition language (XSD). XML and XML Schema provide a convenient format for transferring the contents of a DataSet to and from remote clients.

Sikkim Manipal University

Page No. 241

DOT Net Technologies

Unit 7

Loading a DataSet from XML The contents of an ADO.NET DataSet can be created from an XML stream or document. In addition, with the .NET Framework you have great flexibility over what information is loaded from XML, and how the schema or relational structure of the DataSet is created. To fill a DataSet with data from XML, use the ReadXml method of the DataSet object. The ReadXml method reads from a file, a stream, or an XmlReader, and takes as arguments the source of the XML plus an optional XmlReadMode argument. The ReadXml method reads the contents of the XML stream or document and loads the DataSet with data. It will also create the relational schema of the DataSet depending on the XmlReadMode specified and whether or not a relational schema already exists. The following table describes the options for the XmlReadMode argument.
Option Auto Description This is the default. Examines the XML and chooses the most appropriate option in the following order: If the XML is a DiffGram, DiffGram is used. If the DataSet contains a schema or the XML contains an inline schema, ReadSchema is used. If the DataSet does not contain a schema and the XML does not contain an inline schema, InferSchema is used. If you know the format of the XML being read, for best performance it is recommended that you set an explicit XmlReadMode, rather than accept the Auto default. Reads any inline schema and loads the data and schema. If the DataSet already contains a schema, new tables are added from the inline schema to the existing schema in the DataSet. If any tables in the inline schema already exist in the DataSet, an exception is thrown. You will not be able to modify the schema of an existing table using XmlReadMode.ReadSchema. If the DataSet does not contain a schema, and there is no inline schema, no data is read. Inline schema can be defined using XML Schema definition language (XSD) schema.

ReadSchema

Sikkim Manipal University

Page No. 242

DOT Net Technologies

Unit 7

IgnoreSchema

Ignores any inline schema and loads the data into the existing DataSet schema. Any data that does not match the existing schema is discarded. If no schema exists in the DataSet, no data is loaded. If the data is a DiffGram, IgnoreSchema has the same functionality as DiffGram. Ignores any inline schema and infers the schema per the structure of the XML data, then loads the data. If the DataSet already contains a schema, the current schema is extended by adding columns to existing tables. Extra tables will not be added if there are not existing tables. An exception is thrown if an inferred table already exists with a different namespace, or if any inferred columns conflict with existing columns. Reads a DiffGram and adds the data to the current schema. DiffGram merges new rows with existing rows where the unique identifier values match. Continues reading multiple XML fragments until the end of the stream is reached. Fragments that match the DataSet schema are appended to the appropriate tables. Fragments that do not match the DataSet schema are discarded.

InferSchema

DiffGram

Fragment

DTD Entities If your XML contains entities defined in a document type definition (DTD) schema, an exception will be thrown if you attempt to load a DataSet by passing a file name, stream, or non-validating XmlReader to ReadXml. Instead, you must create an XmlValidatingReader, with EntityHandling set to EntityHandling.ExpandEntities, and pass your XmlValidatingReader to ReadXml. The XmlValidatingReader will expand the entities prior to being read by the DataSet. The following code examples show how to load a DataSet from an XML stream. The first example shows a file name being passed to the ReadXml method. The second example shows a string that contains XML being loaded using a StringReader.
C# Code DataSet dataSet = new DataSet(); dataSet.ReadXml("input.xml", XmlReadMode.ReadSchema); Sikkim Manipal University Page No. 243

DOT Net Technologies

Unit 7

If you call ReadXml to load a very large file, you may encounter slow performance. To ensure best performance for ReadXml, on a large file, call the BeginLoadData method for each table in the DataSet, and then call ReadXml. Finally, call EndLoadData for each table in the DataSet, as shown in the following example.

If the XSD schema for your DataSet includes a targetNamespace, data may not be read, and you may encounter exceptions, when calling ReadXml to load the DataSet with XML that contains elements with no
Sikkim Manipal University Page No. 244

DOT Net Technologies

Unit 7

qualifying namespace. To read unqualified elements in this case, set elementFormDefault equal to "qualified" in your XSD schema. For example: <xsd:schema id="customDataSet" elementFormDefault="qualified" targetNamespace="http://www.tempuri.org/customDataSet.xsd" xmlns="http://www.tempuri.org/customDataSet.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> </xsd:schema>

Merging Data from XML If the DataSet already contains data, the new data from the XML is added to the data already present in the DataSet. ReadXml does not merge from the XML into the DataSet any row information with matching primary keys. To overwrite existing row information with new information from XML, use ReadXml to create a new DataSet, and then Merge the new DataSet into the existing DataSet. Note that loading a DiffGram using ReadXML with an XmlReadMode of DiffGram will merge rows that have the same unique identifier. Deriving DataSet Relational Structure from XML Schema (XSD) This section provides an overview of how the relational schema of a DataSet is built from an XML Schema definition language (XSD) schema document. In general, for each complexType child element of a schema element, a table is generated in the DataSet. The table structure is determined by the definition of the complex type. Tables are created in the DataSet for top-level elements in the schema. However, a table is only created for a top-level complexType element when the complexType element is nested inside another complexType element, in which case the
Sikkim Manipal University Page No. 245

DOT Net Technologies

Unit 7

nested complexType element is mapped to a DataTable within the DataSet. The following example demonstrates an XML Schema where customers is the child element of the MyDataSet element, which is a DataSet element. <xs:schema id="SomeID" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="MyDataSet" msdata:IsDataSet="true"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="customers" > <xs:complexType > <xs:sequence> <xs:element name="CustomerID" type="xs:integer" minOccurs="0" />

<xs:element name="CompanyName" type="xs:string" minOccurs="0" /> <xs:element name="Phone" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> In the preceding example, the element customers is a complex type element. Therefore, the complex type definition is parsed, and the mapping process creates the following table. Customers (CustomerID , CompanyName, Phone)

Sikkim Manipal University

Page No. 246

DOT Net Technologies

Unit 7

The data type of each column in the table is derived from the XML Schema type of the corresponding element or attribute specified. Note: If the element customers is of a simple XML Schema data type such as integer, no table is generated. Tables are only created for the top-level elements that are complex types. In the following XML Schema, the Schema element has two element children, InStateCustomers and OutOfStateCustomers. <xs:schema id="SomeID" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="InStateCustomers" type="customerType" /> <xs:element name="OutOfStateCustomers" type="customerType" /> <xs:complexType name="customerType" > </xs:complexType> <xs:element name="MyDataSet" msdata:IsDataSet="true"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element ref="customers" /> </xs:choice> </xs:complexType> </xs:element> </xs:schema> Both the InStateCustomers and the OutOfStateCustomers child elements are complex type elements (customerType). Therefore, the mapping process generates the following two identical tables in the DataSet InStateCustomers (CustomerID , CompanyName, Phone) OutOfStateCustomers (CustomerID , CompanyName, Phone) Mapping XML Schema (XSD) Constraints to DataSet Constraints The XML Schema definition language (XSD) allows constraints to be specified on the elements and attributes it defines. When mapping an XML
Sikkim Manipal University Page No. 247

DOT Net Technologies

Unit 7

Schema to relational schema in a DataSet, XML Schema constraints are mapped to appropriate relational constraints on the tables and columns within the DataSet. This section discusses the mapping of the following XML Schema constraints: The uniqueness constraint specified using the unique element. The key constraint specified using the key element. The keyref constraint specified using the keyref element.

By using a constraint on an element or attribute, you specify certain restrictions on the values of the element in any instance of the document. For example, a key constraint on a CustomerID child element of a Customer element in the schema indicates that the values of the CustomerID child element must be unique in any document instance, and that null values are not allowed. Constraints can also be specified between elements and attributes in a document, in order to establish a relationship within the document. The key and keyref constraints are used in the schema to specify the constraints within the document, resulting in a relationship between document elements and attributes. The mapping process converts these schema constraints into appropriate constraints on the tables created within the DataSet. Map unique XML Schema (XSD) Constraints to DataSet Constraints In an XML Schema definition language (XSD) schema, the unique element specifies the uniqueness constraint on an element or attribute. In the process of translating an XML Schema into a relational schema, the unique constraint specified on an element or attribute in the XML Schema is mapped to a unique constraint in the DataTable in the corresponding DataSet that is generated.
Sikkim Manipal University Page No. 248

DOT Net Technologies

Unit 7

The following table outlines the msdata attributes that you can specify in the unique element.
Attribute name msdata:ConstraintName Description If this attribute is specified, its value is used as the constraint name. Otherwise, the name attribute provides the value of the constraint name. If PrimaryKey="true" is present in the unique element, a unique constraint is created with the IsPrimaryKey property set to true.

msdata:PrimaryKey

The following example shows an XML Schema that uses the unique element to specify a uniqueness constraint.

</xs:complexType> <xs:unique msdata:ConstraintName="UCustID" name="UniqueCustIDConstr" > <xs:selector xpath=".//Customers" /> <xs:field xpath="CustomerID" /> </xs:unique> </xs:element> </xs:schema> The unique element in the schema specifies that for all Customers elements in a document instance, the value of the CustomerID child element must be unique. In building the DataSet, the mapping process reads this schema and generates the following table:
Sikkim Manipal University Page No. 249

DOT Net Technologies

Unit 7

Customers (CustomerID, CompanyName, Phone) The mapping process also creates a unique constraint on the CustomerID column, as shown in the following DataSet. (For simplicity, only relevant properties are shown.) DataSetName: MyDataSet TableName: Customers ColumnName: CustomerID AllowDBNull: True Unique: True ConstraintName: UcustID Type: UniqueConstraint Table: Customers Columns: CustomerID IsPrimaryKey: False

In the DataSet that is generated, the IsPrimaryKey property is set to False for the unique constraint. The unique property on the column indicates that the CustomerID column values must be unique (but they can be a null reference, as specified by the AllowDBNull property of the column). If you modify the schema and set the optional msdata:PrimaryKey attribute value to True, the unique constraint is created on the table. The AllowDBNull column property is set to False, and the IsPrimaryKey property of the constraint set to True, thus making the CustomerID column a primary key column. You can specify a unique constraint on a combination of elements or attributes in the XML Schema. The following example demonstrates how to specify that a combination of CustomerID and CompanyName values must be unique for all Customers in any instance, by adding another xs:field element in the schema.

Sikkim Manipal University

Page No. 250

DOT Net Technologies

Unit 7

<xs:unique msdata:ConstraintName="SomeName" name="UniqueCustIDConstr" > <xs:selector xpath=".//Customers" /> <xs:field xpath="CustomerID" /> <xs:field xpath="CompanyName" /> </xs:unique> This is the constraint that is created in the resulting DataSet. ConstraintName: SomeName Table: Customers Columns: CustomerID CompanyName IsPrimaryKey: False Generating DataSet Relations from XML Schema (XSD) In a DataSet, you form an association between two or more columns by creating a parent-child relation. There are three ways to represent a DataSet relation within an XML Schema definition language (XSD) schema: Specify nested complex types. Use the msdata:Relationship annotation. Specify an xs:keyref without the msdata:ConstraintOnly annotation.

Nested Complex Types Nested complex type definitions in a schema indicate the parent-child relationships of the elements. The following XML Schema fragment shows that OrderDetail is a child element of the Order element. <xs:element name="Order"> <xs:complexType> <xs:sequence> <xs:element name="OrderDetail" /> <xs:complexType> </xs:complexType> </xs:sequence> </xs:complexType> </xs:element>

Sikkim Manipal University

Page No. 251

DOT Net Technologies

Unit 7

msdata:Relationship Annotation The msdata:Relationship annotation allows you to explicitly specify parentchild relationships between elements in the schema that are not nested. The following example shows the structure of the Relationship element. <msdata:Relationship name="CustOrderRelationship" msdata:parent="" msdata:child="" msdata:parentkey="" msdata:childkey="" /> <xs:element name="MyDataSet" msdata:IsDataSet="true"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="OrderDetail"> <xs:complexType> </xs:complexType> </xs:element> <xs:element name="Order"> <xs:complexType> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> <xs:annotation> <xs:appinfo> <msdata:Relationship name="OrdOrdDetailRelation" msdata:parent="Order">

The mapping process uses the Relationship element to create a parentchild relationship between the OrderNumber column in the Order table and the OrderNo column in the OrderDetail table in the DataSet. The mapping process only specifies the relationship; it does not automatically specify any constraints on the values in these columns, as do the primary key/foreign key constraints in relational databases.

Sikkim Manipal University

Page No. 252

DOT Net Technologies

Unit 7

7.10 Summary
This unit provides with an overview of the features of ADO.NET. It makes the user comfortable with developing database applications in a disconnected architecture. It also introduces the user with various ways of connecting to a data source using ADO.NET. It introduces the concept of connection strings and connection string builders in ADO.NET. It then takes the user through the concepts of namespaces and classes in ADO.NET. It demonstrates the usage of the feature DataAdapter in fetching the data from any database using ADO.NET. It then demonstrates how XML data can be used with ADO.NET.

Self Assessment Questions 1. The _____ was first introduced in version 1.0 of the .NET framework, that provided an extensive array of features to handle live data in a connected mode or data that is disconnected from its underlying data store. 2. ADO.NET is the database language spoken by ______ applications. 3. In __________ architecture, data is retrieved from a database and cached on your local machine. You manipulate the data on your local computer and connect to the database only when you wish to alter records or acquire new data. 4. The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes found in ________. 5. The .NET Framework Data Provider for OLE DB uses the ____________ namespace. 6. The ______ is a helper object that automatically generates command properties of a DataAdapter or derives parameter information from a stored procedure and populates the Parameters collection of a Command object.
Sikkim Manipal University Page No. 253

DOT Net Technologies

Unit 7

7. The _______ driver is the Microsoft OLE DB provider for Oracle. 8. The _____ block in Visual Basic or C# automatically disposes of the connection when the code exits the block, even in the case of an unhandled exception.

7.11 Terminal Questions


1. Describe the process of connection establishment to a data source using ADO.NET. (Refer to 7.2) 2. Discuss about Connection String Builders in ADO.NET (Refer to 7.4) 3. Write the basic features of ADO.NET (Refer to 7.6) 4. Write about the combined usage of XML and ADO.NET (Refer to 7.9)

7.12 Answers to Self Assessment Questions


1. ADO.NET 2. managed 3. disconnected 4. System.Xml.dll 5. System.Data.OleDb 6. CommandBuilder 7. MSDAORA 8. Using

Sikkim Manipal University

Page No. 254

Вам также может понравиться