ADO.
NET
.NET Data Access and Manipulation
Unit 3
What is [Link]?
[Link] is an object-oriented set of libraries that allows you to
interact with data sources.
A data-access technology that enables applications to connect to
data stores and manipulate data contained in them in various ways
Former version was ADO (ActiveX Data Object)
Namespaces used with [Link] include:
[Link]
[Link]
[Link]
ADO / [Link] Comparisons
Feature ADO [Link]
In memory data Recordset object Dataset object
storage Mimics single table Contains DataTables
Data Reads Sequential Sequential or non-sequential
Data Sources OLE/DB via the Connection Managed provider calls the
object SQL APIs
Disconnected data Limited support, suitable for Strong support, with updating
R/O
Passing datasets COM marshalling DataSet support for XML
passing
Scalability Limited Disconnected access provides
scalability
[Link] Architecture
[Link] Core Objects
Object Description
Connection Establishes a connection to a specific data source. (Base
class: DbConnection)
Command Executes a command against a data source. Exposes
Parameters and can execute within the scope of a
Transaction from a Connection. (The base class:
DbCommand)
DataReader Reads a forward-only, read-only stream of data from a data
source. (Base class: DbDataReader)
DataAdapter Populates a DataSet and resolves updates with the data
source. (Base class: DbDataAdapter)
DataTable Has a collection of DataRows and DataColumns
representing table data, used in disconnected model
DataSet Represents a cache of data. Consists of a set of DataTables
and relations among them
.NET Framework data providers:
• A .NET Framework data provider is used for connecting to a database,
executing commands, and retrieving results.
• .NET Framework data providers are lightweight, creating a minimal layer
between the data source and code, increasing performance without sacrificing
functionality.
• The following table lists the data providers that are included in the .NET
Framework.
.NET Framework data providers:
.NET Framework data provider Description
.NET Framework Data Provider for SQL Provides data access for Microsoft SQL Server. Uses
Server the [Link] namespace.
.NET Framework Data Provider for For data sources exposed by using OLE DB. Uses
OLE DB the [Link] namespace.
.NET Framework Data Provider for For data sources exposed by using ODBC. Uses
ODBC the [Link] namespace.
.NET Framework Data Provider for For Oracle data sources. The .NET Framework Data Provider for
Oracle Oracle supports Oracle client software version 8.1.7 and later, and
uses the [Link] namespace.
EntityClient Provider Provides data access for Entity Data Model (EDM) applications.
Uses the [Link] namespace.
.NET Framework Data Provider for SQL Provides data access for Microsoft SQL Server Compact 4.0. Uses
Server Compact 4.0. the [Link] 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 Description
Connection Establishes a connection to a specific data source. The base class for
all Connection objects is the DbConnection class.
Command 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.
DataReader Reads a forward-only, read-only stream of data from a data source.
The base class for all DataReader objects is the DbDataReader class.
DataAdapter Populates a DataSet and resolves updates with the data source. The
base class for all DataAdapter objects is the DbDataAdapter class.
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 Description
Transaction Enlists commands in transactions at the data source. The base class for
all Transaction objects is the DbTransaction class. [Link] also provides
support for transactions using classes in the [Link] namespace.
CommandBuilder 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.
ConnectionStringBuilder 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.
Parameter Defines input, output, and return value parameters for commands and stored
procedures. The base class for all Parameter objects is the DbParameter class.
Exception 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.
Error Exposes the information from a warning or error returned by a data source.
ClientPermission Provided for .NET Framework data provider code access security attributes. The
base class for all ClientPermission objects is the DBDataPermission class.
Access SQL Server Databases with [Link]
Use classes in the [Link] namespace to
access and manipulate SQL Server databases
Connecting to an SQL Server Database
SqlConnection class: used to connect to an SQL Server database
Create an object from this class, passing in a connection string
Connecting to an SQL Server Database
SqlConnection con = new SqlConnection ("Data Source=.;Initial
Catalog = DatabaseConnectivity;Trusted_Connection=true;");
Connection string must include the Data Source parameter with
the name of the SQL Server instance you wish to use
Initial Catalog: Initial Catalog is the database Name
Trusted_Connection: Trusted_Connection should be true if
you are using window authentication while connecting to
database. If you are using SQL authentication, you will have to
pass userid and password.
Opening and Closing a Data Source
After creating a SqlConnection object, use the Open()
method to open the specified SQL Server database instance
Use the Close() method to disconnect the database
connection
Database connections do not automatically close when an
[Link] program ends
Eg. [Link]()
Eg. [Link]()
Creating Database in Sql Server
Step1 –Go to Server Explorer and right click data Connections to
create new sql server database
Creating Database in Sql Server
Step2- Select data source—
Microsoft SQL Server Database
File
Step3- Enter database name
then click on ok so a new
database with that name will be
created
Creating Database in Sql
Server
Step 4-Now right click Table to create
new table inside [Link] database
Step 5-Enter number of columns and
then save the table
Creating Database in Sql
Server
Now you can see after saving table
Table2 is created in [Link]
Step 6 right click table and select
show table data to enter row in table
Using Exception Handling to Control
SQL Server Errors
Place the Open() method within a try…catch block
to trap connection errors
SqlException class:
Part of the [Link] namespace
Represents the exception that is thrown when SQL
Server returns an error or warning
Number and Message properties provide an error code
and message for the exception
Using Exception Handling to Control SQL
Server Errors (cont’d.)
Figure 8-1 Error number and message generated by an invalid user ID
Executing SQL Commands through [Link]
[Link] namespace contains
classes to access and manipulate SQL Server
databases:
SqlDataReader class
SqlCommand class
SqlCommand class
SqlCommand class: used to execute commands against Microsoft
SQL Server
Syntax 1:
SqlCommand object = new SqlCommand(“command”, connection)
command parameter: contains the SQL command to be executed
connection parameter: represents the SqlConnection object used
to connect to the database
Syntax 2:
SqlCommand cmd = new SqlCommand();
[Link] = conn;
[Link] = “select * from Table1”;
SqlCommand class
ExecuteNonQuery() method of the SqlCommand object:
executes commands against a database
Used for inserting, updating, or deleting rows in a SQL Server
database. Does not return a recordset of data
ExecuteScalar() : The ExecuteScalar() returns a single value
from the database. Generally it is used with an aggregate
function (a function which returns a single value).
ExecuteReader() : The ExecuteReader() method can
return a set of records from a database.
DataAdapter class
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\
Krupa Shah\\Documents\\[Link];Integrated Security=True;Connect Timeout=30;User
Instance=True";
SqlConnection connection = new SqlConnection(connectionString);
string sql = "select * from stuinfo";
[Link]();
SqlCommand cmd = new SqlCommand(sql, connection);
SqlDataAdapter adapter =new SqlDataAdapter(cmd);
DataSet ds =new DataSet();
[Link](ds);
int i=0,cnt = [Link][0].[Link]-1;
while(cnt>=0)
{
[Link]([Link][0].Rows[i++].ItemArray[0].ToString());
cnt--;
}
[Link]();
SqlDataReader class
The SqlDataReader Object is a stream-based , forward-only,
read-only retrieval of query results from the Data Source, which
do not update the data it contains.
The SqlDataReader cannot be created directly from code, they
can created only by calling the ExecuteReader method of a C#
Command Object.
SqlDataReader class-Example
When a user clicks display button data from database
is loaded in DropDownList controls on form
string connectionString = "Data Source=.\\
SQLEXPRESS;AttachDbFilename=C:\\Users\\Krupa Shah\\
Documents\\[Link];Integrated Security=True;Connect
Timeout=30;User Instance=True";
SqlConnection connection = new SqlConnection(connectionString);
string sql = "select * from stuinfo";
[Link]();
SqlCommand cmd = new SqlCommand(sql, connection);
SqlDataReader reader = [Link]();
while ([Link]())
{
[Link]([Link](0).ToString());
[Link]([Link](1).ToString());
}
[Link]();
[Link]();