Anda di halaman 1dari 18

ADO.

NET

ADO.NET OVERVIEW

ADO (ActiveX Data Objects) is a library of COM components that has had many incarnations over the last few years. Currently at version 2.7, ADO consists primarily of the Connection, Command, Recordset, and Field objects. Using ADO, a connection is opened to the database, some data is selected into a record set consisting of fields, that data is then manipulated and updated on the server, and the connection is closed. ADO also introduced a so-called disconnected record set, which is used when keeping the connection open for long periods of time is not desirable There were several problems that ADO did not address satisfactorily, most notably the unwieldiness (in physical size) of a disconnected record set. This support was more necessary than ever with the evolution of Web-centric computing, so a fresh approach was required.

ADO.NET AND THE .NET FRAMEWORK


Microsoft .NET Framework
Web Services User Interface

Data and XML ADO.NET Base Classes Common Language Runtime XML ... ...

ADO.NET ships with four database client namespaces: one for SQL Server, another for Oracle, the third for ODBC data sources, and the fourth for any database exposed through OLE DB. If your database of choice is not SQL Server or Oracle, the OLE DB route should be taken unless you have no other choice than to use ODBC.
Brief Description All generic data access classes Classes shared (or overridden) by individual data providers ODBC provider classes OLE DB provider classes New base classes and connection factory classes Oracle provider classes New generic interfaces and classes for SQL Server data access SQL Server provider classes SQL Server data types

Namespaces
Namespace System.Data System.Data.Common System.Data.Odbc System.Data.OleDb System.Data.ProviderBase System.Data.Oracle System.Data.Sql System.Data.SqlClient System.Data.SqlTypes

SHARED CLASSES

ADO.NET contains a number of classes that are used regardless of whether you are using the SQL Server classes or the OLE DB classes.

Class
DataSet

Description
This object is designed for disconnected use and can contain a set of DataTables and include relationships between these tables. A container of data that consists of one or more DataColumns and, when populated, will have one or more DataRows containing data. A number of values, akin to a row from a database table, or a row from a spreadsheet. This object contains the definition of a column, such as the name and data type. A link between two DataTable classes within a DataSet class. Used for foreign key and master/detail relationships. This class defines a rule for a DataColumn class (or set of data columns), such as unique values.

DataTable

DataRow DataColumn DataRelation

Constraint

DATABASE-SPECIFIC CLASSES

In addition to the shared classes introduced in the previous section, ADO.NET contains a number of database-specific classes. These classes implement a set of standard interfaces defined within the System.Data namespace, allowing the classes to be used in a generic manner if necessary. For example, both the SqlConnection and OleDbConnection classes implement the IDbConnection interface.
Classes SqlCommand, OleDbCommand, OracleCommand, and ODBCCommand SqlCommandBuilder, OleDbCommandBuilder, OracleCommandBuilder, and ODBCCommandBuilder SqlConnection, OleDbConnection, OracleConnection, and ODBCConnection SqlDataAdapter, OleDbDataAdapter, OracleDataAdapter, and ODBCDataAdapter Description Used as wrappers for SQL statements or stored procedure calls. Examples for the SqlCommand class are shown later in the chapter. Used to generate SQL commands (such as INSERT, UPDATE, and DELETE statements) from a SELECT statement. Used to connect to the database. Similar to an ADO Connection. Examples are shown later in the chapter. Used to hold select, insert, update, and delete commands, which are then used to populate a DataSet and update the database. Examples of the SqlDataAdapter are presented in this chapter. Used as a forward only, connected data reader. Some examples of the SqlDataReader are shown in this chapter. Used to define a parameter to a stored procedure. Examples of how to use the SqlParameter class are shown in this chapter. Used for a database transaction, wrapped in an object.

SqlDataReader, OleDbDataReader, OracleDataReader, and ODBCDataReader SqlParameter, OleDbParameter, OracleParameter, and ODBCParameter SqlTransaction, OleDbTransaction, OracleTransaction, and ODBCTransaction

USING DATABASE CONNECTIONS


To access the database, you need to provide connection parameters, such as the machine that the database is running on and possibly your login credentials. Anyone who has worked with ADO will be familiar with the .NET connection classes:

OleDbConnection and y SqlConnection.


y

THE

FOLLOWING CODE ILLUSTRATES HOW TO CREATE, OPEN, AND CLOSE A CONNECTION TO THE NORTHWIND DATABASE:

using System.Data.SqlClient; string source = "server=(local);" + "integrated security=SSPI;" + "database=Northwind"; SqlConnection conn = new SqlConnection(source); conn.Open(); // Do something useful conn.Close();

server=(local) - This denotes the database server to connect to. SQL Server permits a number of separate database server instances to be running on the same machine, and here youre connecting to the default SQL Server instance. If you are using SQL Express, change the server part to server=./sqlexpress. integrated security=SSPI - This uses Windows Authentication to connect to the database, which is highly recommended over using a username and password within the source code. database=Northwind - This describes the database instance to connect to; each SQL Server process can expose several database instance

COMMANDS

A command is, in its simplest form, a string of text containing SQL statements that is to be issued to the database. A command could also be a stored procedure, or the name of a table that will return all columns and all rows from that table
string source = "server=(local);" + "integrated security=SSPI;" + "database=Northwind"; string select = "SELECT ContactName,CompanyName FROM Customers"; SqlConnection conn = new SqlConnection(source); conn.Open(); SqlCommand cmd = new SqlCommand(select, conn);

CommandType
Text (default)

Example
String select = SELECT ContactName FROM Customers; SqlCommand cmd = new SqlCommand(select , conn); SqlCommand cmd = new SqlCommand(CustOrderHist, conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue(@CustomerID, QUICK); OleDbCommand cmd = new OleDbCommand(Categories, conn); cmd.CommandType = CommandType.TableDirect;

StoredProcedure

TableDirect

Executing Commands After you have defined the command, you need to execute it. A number of ways exist to issue the statement, depending on what you expect to be returned (if anything) from that command. The <provider>Command classes provide the following execute methods: ExecuteNonQuery() - Executes the command but does not return any output ExecuteReader() - Executes the command and returns a typed IDataReader ExecuteScalar() - Executes the command and returns a single value

EXECUTENONQUERY()

This method is commonly used for UPDATE, INSERT, or DELETE statements, where the only returned value is the number of records affected.
using System;
using System.Data.SqlClient; public class ExecuteNonQueryExample { public static void Main(string[] args) { string source = "server=(local);" + "integrated security=SSPI;" + "database=Northwind";
string select = "UPDATE Customers SET ContactName = 'Bob WHERE ContactName = 'Bill'";

SqlConnection conn = new SqlConnection(source); conn.Open(); SqlCommand cmd = new SqlCommand(select, conn); int rowsReturned = cmd.ExecuteNonQuery(); Console.WriteLine("{0} rows returned.", rowsReturned); conn.Close(); } }

ExecuteNonQuery() returns the number of rows affected by the command as an int

EXECUTEREADER()

This method executes the command and returns a typed data reader object, depending on the provider in use. using System; using System.Data.SqlClient; public class ExecuteReaderExample { public static void Main(string[] args) { string source = "server=(local);" + "integrated security=SSPI;" + "database=Northwind"; string select = "SELECT ContactName,CompanyName FROM Customers"; SqlConnection conn = new SqlConnection(source); conn.Open(); SqlCommand cmd = new SqlCommand(select, conn); SqlDataReader reader = cmd.ExecuteReader(); while(reader.Read()) { Console.WriteLine("Contact : {0,-20} Company : {1}" , reader[0] , reader[1]); } } }

EXECUTESCALAR()

On many occasions, it is necessary to return a single result from a SQL statement, such as the count of records in a given table, or the current date/time on the server. The ExecuteScalar method can be used in such situations:
using System; using System.Data.SqlClient; public class ExecuteScalarExample { public static void Main(string[] args) { string source = "server=(local);" + "integrated security=SSPI;" + "database=Northwind"; string select = "SELECT COUNT(*) FROM Customers"; SqlConnection conn = new SqlConnection(source); conn.Open(); SqlCommand cmd = new SqlCommand(select, conn); object o = cmd.ExecuteScalar(); Console.WriteLine ( o ) ; } }

ADDING PARAMETERS IN QUERY


using System; using System.Data.SqlClient; public class ExecuteReaderExample { public static void Main(string[] args) { string source = "server=(local);" + "integrated security=SSPI;" + "database=Northwind"; string select = "SELECT * FROM Customers WHERE CustID = @CustID"; SqlConnection conn = new SqlConnection(source); conn.Open(); SqlCommand cmd = new SqlCommand(select, conn); cmd.Parameters.AddWithValue(@CustID,1); SqlDataReader reader = cmd.ExecuteReader(); while(reader.Read()) { Console.WriteLine("Contact : {0,-20} Company : {1}" , reader[0] , reader[1]); } } }

MANAGING DATA AND RELATIONSHIPS: THE DATASET CLASS


The DataSet class has been designed as an offline container of data. It has no notion of database connections A DataSet class consists of a set of data tables, each of which will have a set of data columns and data rows

DATASET EXAMPLE
using System; using System.Data.SqlClient; public class datasetExp { public static void Main(string[] args) { string source = "server=(local);" + "integrated security=SSPI;" + "database=Northwind"; string select = "SELECT ContactName,CompanyName FROM Customers"; SqlConnection conn = new SqlConnection(source); SqlDataAdapter da = new SqlDataAdapter(select, conn); DataSet ds = new DataSet(); da.Fill(ds , Customer); foreach ( DataRow dr in ds.Table[Customer].Rows) { Console.WriteLine( {0} .{1} , dr[0] ,dr[1]); } } } }

SUMMARY
ADO.NET is the evolution of ADO It is a disconnected, Web-centric model Flexible in its ability to work with data Increases your ability to logically organize data Extensive support for XML Interacts with a wide variety of data sources

Anda mungkin juga menyukai