Sie sind auf Seite 1von 41

WELL COME TO ALL

ADO.NET OVERVIEW

TAKEN BY,
M.STEPHEN,MCA.

Introduction to
Microsoft ADO.NET

Part1: Overview

Overview of ADO.NET

Creating a Connection to a Database

Displaying a DataSet in a List-Bound Control

Lesson: Overview of ADO.NET

What is ADO.NET?

Using Namespaces

The ADO.NET Object Model

What is a DataSet?

Accessing Data with ADO.NET

Practice: Identifying ADO.NET Components

What is ADO.NET?
ADO.NET provides a set of classes for working with
data. ADO.NET provides:

A system designed for disconnected environments

A programming model with advanced XML support

A set of classes, interfaces, structures, and


enumerations that manage data access from within
the .NET Framework

Using Namespaces

Use the Imports or using statement to import namespaces


Imports
Imports
Imports
Imports
using
using
using
using

System.Data
System.Data
System.Data.SqlClient
System.Data.SqlClient

System.Data;
System.Data;
System.Data.SqlClient;
System.Data.SqlClient;

Namespaces used with ADO.NET include:

System.Data

System.Data.SqlClient

System.Data.OleDb

The ADO.NET Object Model


DataTable

DataSet
DataTable

SqlDataAdapter
OleDbDataAdapter

SQL Server .NET


Data Provider

OLE DB .NET
Data Provider
OleDbConnection

SqlConnection

SQL Server 7.0


(and later)

OLEDB sources
(SQL Server 6.5)

What is a Dataset?
DataSet
DataTable
DataTable

DataTable

SqlDataAdapter

SqlConnection

SQL Server 2000

Web server memory


Physical storage
OleDbDataAdapter

OleDbConnectio
n

OleDb Database

Accessing Data with ADO.NET


11
1.
2.
22

Client makes request

3.
33

Fill the DataSet from the DataAdapter


and close the connection
Return the DataSet to the Client

4.
44
5.
55
6.
66
7.
77

Create the SqlConnection and SqlDataAdapter objects


Web
Webserver
server

Database

SqlConnection

SqlDataAdapter

Client manipulates the data


Update the DataSet
Use the SqlDataAdapter to open
the SqlConnection, update the
database, and close the
connection
List-Bound
List-Bound
Control
Control

Client
Client

DataSet

The DataAdapter Object Model


DataSet
DataSet
DataAdapter
SelectCommand

UpdateCommand

InsertCommand

DeleteCommand

Command
Command

Command
Command

Command
Command

DataReader
DataReader
Command
Command

Connection
Connection
sp_SELECT

sp_UPDATE

sp_INSERT
Database

sp_DELETE

Generating a DataSet

You can generate a DataSet

through the UI
Creates a DataSet that allows you to access
data as an object

or through code

Dim
Dim ds
ds As
As New
New DataSet()
DataSet()
DataSet
DataSet ds
ds == new
new DataSet();
DataSet();

and then fill


DataAdapter1.Fill(ds)
DataAdapter1.Fill(ds)
DataAdapter2.Fill(ds)
DataAdapter2.Fill(ds)
DataAdapter1.Fill(ds);
DataAdapter1.Fill(ds);
DataAdapter2.Fill(ds);
DataAdapter2.Fill(ds);

Displaying a DataSet in a List-Bound Control

What are List-Bound Controls?

Displaying DataSet Data in List-Bound Controls

Demonstration: Binding List-Bound Controls to a


Database

Practice: Using a DataGrid

Demonstration: Customizing the DataGrid Control

What are List-Bound Controls?

Controls that connect to a data source and display the


data

List-bound controls include the following:

DropDownList

DataGrid

ListBox

DataList

CheckBoxList

Repeater

RadioButtonList

Displaying DataSet Data in List-Bound Controls

Set the properties


Property
Property

DataSource
DataSource
DataMember
DataMember
DataTextField
DataTextField
DataValueField
DataValueField

Description
Description
The
TheDataSet
DataSet containing
containingthe
thedata
data
The
TheDataTable
DataTableininthe
theDataSet
DataSet
The
Thefield
fieldininthe
the DataTable
DataTable that
thatisisdisplayed
displayed
The
Thefield
fieldininthe
the DataTable
DataTable that
thatbecomes
becomesthe
the
value
valueofofthe
theselected
selecteditem
itemininthe
thelist
list

Fill the DataSet, then call the DataBind method


DataAdapter1.Fill(ds)
DataAdapter1.Fill(ds)
lstEmployees.DataBind()
lstEmployees.DataBind()
DataAdapter1.Fill(ds);
DataAdapter1.Fill(ds);
lstEmployees.DataBind();
lstEmployees.DataBind();

Overview

Introduction to Using ADO.NET

Connecting to a Database

Accessing Data with DataSets

Using Multiple Tables

Accessing Data with DataReaders

Lesson: Introduction to Using ADO.NET

Multimedia: The ADO.NET Object Model

Using DataSets vs. DataReaders

Practice: When to Use DataSets or DataReaders

Multimedia: The ADO.NET Object Model

Using DataSets vs. DataReaders

DataSet

DataReader

Read/write access to data

Read-only

Includes multiple tables from


different databases

Based on one SQL statement


from one database

Disconnected

Connected

Bind to multiple controls

Bind to one control only

Forward and backward scanning


of data

Forward-only

Slower access

Faster access

Lesson: Connecting to a Database

SQL Server Security

Creating the Connection

Demonstration: Setting SQL Server Security

SQL Server Security


Web
WebServer
Server
Default
DefaultASP.NET
ASP.NETsettings
settings
Here is the
username and
password

Mixed
Mixedmode
mode
authentication
authentication

or
or
Client

Windows
Windowsonly
only
authentication
authentication
Web
WebServer
Server
Windows
Windowsauthentication
authentication

Send the username


and password in
clear text.
SQL
SQLServer
Server
Each
Eachuser
useraccount
accountadded
added
totoSQL
SQLServer
Serverlogins
loginsgroup
group
Do not send the
username and
password.
Just send that the user
has been authenticated.
SQL
SQLServer
Server
Only
OnlyASPNET
ASPNETaccount
account
isisgranted
grantedaccess
access

Creating the Connection

Using SqlConnection
Dim
Dim con
con as
as new
new connection()
connection()
Con.connectionstring=database=master;server=ORION;
Con.connectionstring=database=master;server=ORION;
Uid=sample;pwd=sample;
Uid=sample;pwd=sample;
Con.open()
Con.open()

Setting connection string parameters

Data Base
Server
User ID

Password

Provider

Lesson: Accessing Data with DataSets

Creating a DataAdapter

Creating a DataSet

Demonstration: Programmatically Using a DataSet

Using a DataView

Practice: Organizing Code to Create a DataSet

Binding a DataSet to a List-Bound Control

Instructor-Led Practice: Displaying a DataSet

Handling Errors

Creating a DataAdapter

Store the query in a DataAdapter


Dim
Dim da
da As
As New
New SqlDataAdapter
SqlDataAdapter
("select
("select ** from
from Authors",
Authors", conn)
conn)
SqlDataAdapter
SqlDataAdapter da
da == new
new SqlDataAdapter
SqlDataAdapter
("select
("select ** from
from Authors",conn);
Authors",conn);

The DataAdapter constructor sets the SelectCommand property


da.SelectCommand.CommandText
da.SelectCommand.CommandText
da.SelectCommand.Connection
da.SelectCommand.Connection

da.SelectCommand.CommandText;

da.SelectCommand.CommandText;
Set the InsertCommand,
UpdateCommand, and DeleteCommand
da.SelectCommand.Connection;
da.SelectCommand.Connection;
properties if needed

Creating a DataSet

Create and populate a DataSet with DataTables

Fill method executes the SelectCommand

DataSet
DataSet ds
ds == new
new DataSet();
DataSet();
da.Fill(ds,
da.Fill(ds, "Authors");
"Authors");

Dim
Dim ds
ds As
As New
New DataSet()
DataSet()
da.Fill(ds,
da.Fill(ds, "Authors")
"Authors")

Access a DataTable

ds.Tables["Authors"].Rows.Count;
ds.Tables["Authors"].Rows.Count;
string
string str="";
str="";
foreach(DataRow
foreach(DataRow rr in
in
ds.Tables["Authors"].Rows)
ds.Tables["Authors"].Rows)
{{
str
str +=
+= r[2];
r[2];
str
+=
r["au_lname"];
str += r["au_lname"];
}}

ds.Tables("Authors").Rows.Count
ds.Tables("Authors").Rows.Count
Dim
Dim rr As
As DataRow
DataRow
Dim
str
As
Dim str As String
String
For
Each
r
in
For Each r in __
ds.Tables("Authors").Rows
ds.Tables("Authors").Rows
str
str &=
&= r(2)
r(2)
str
str &=
&= r("au_lname")
r("au_lname")
Next
Next

Using a DataView

A DataView can be customized to present a subset of


data from a DataTable

The DefaultView property returns the default DataView


of the table
Dim
Dim dv
dv As
As DataView
DataView == ds.Tables("Authors").DefaultView
ds.Tables("Authors").DefaultView
DataView
DataView dv
dv == ds.Tables["Authors"].DefaultView;
ds.Tables["Authors"].DefaultView;

Setting up a different view of a DataSet


Dim
Dim dv
dv As
As New
New DataView
DataView (ds.Tables("Authors"))
(ds.Tables("Authors"))
dv.RowFilter
=
"state
=
dv.RowFilter = "state = 'CA'"
'CA'"
DataView
DataView dv
dv == new
new DataView(ds.Tables["Authors"]);
DataView(ds.Tables["Authors"]);
dv.RowFilter
=
"state
dv.RowFilter = "state == 'CA'";
'CA'";

Binding a DataSet to a List-Bound Control

Create the control


<asp:DataGrid
<asp:DataGrid id="dg"
id="dg" runat="server"
runat="server" />
/>

Bind to a DataSet or a DataView


dg.DataSource
dg.DataSource == ds
ds
dg.DataMember
=
"Authors"
dg.DataMember = "Authors"
dg.DataBind()
dg.DataBind()

dg.DataSource
dg.DataSource == ds;
ds;
dg.DataMember
=
"Authors";
dg.DataMember = "Authors";
dg.DataBind()
dg.DataBind();;

Handling Errors

Connection will not open

Connection string is invalid

Server or database not found

Login failed

DataAdapter cannot create a DataSet

Invalid SQL syntax

Invalid table or field name

Code Example

Lesson: Using Multiple Tables

Storing Multiple Tables

Creating Relationships

Programmatically Navigating Between Tables Using


Relationships

Visually Navigating Between Tables Using


Relationships

Instructor-Led Practice: Displaying Data from Multiple


Tables

Storing Multiple Tables

Add the first table


daCustomers
daCustomers == New
New SqlDataAdapter
SqlDataAdapter __
("select
("select ** from
from Customers",
Customers", conn1)
conn1)
daCustomers.Fill(ds,
daCustomers.Fill(ds, "Customers")
"Customers")

Add the subsequent table(s)


daOrders
daOrders == New
New SqlDataAdapter
SqlDataAdapter __
("select
("select ** from
from Orders",
Orders", conn2)
conn2)
daOrders.Fill(ds,
daOrders.Fill(ds, "Orders")
"Orders")
Customers

conn1

conn2
DataSet

Orders

Creating Relationships

Identify parent column

Dim
Dim parentCol
parentCol As
As DataColumn
DataColumn == __
ds.Tables("Customers").Columns("CustomerID")
ds.Tables("Customers").Columns("CustomerID")

Identify child column

Dim
Dim childCol
childCol As
As DataColumn
DataColumn == __
ds.Tables("Orders").Columns("CustomerID")
ds.Tables("Orders").Columns("CustomerID")

Create DataRelation

parentCol

Dim
Dim dr
dr As
As New
New DataRelation
DataRelation __
("name",
("name", parentCol,
parentCol, __
childCol)
childCol)
ds.DataRelations.Add(dr)
ds.DataRelations.Add(dr)

Customers table

DataSet

DataRelation

childCol
Orders table

Programmatically Navigating Between Tables Using


Relationships
ds.Tables(index).Rows(index).GetChildRows("relation")
ds.Tables(index).Rows(index).GetChildRows("relation")
ds.Tables(index).Rows(index).GetParentRow("relation")
ds.Tables(index).Rows(index).GetParentRow("relation")
ds.Tables[index].Rows[index].GetChildRows("relation");
ds.Tables[index].Rows[index].GetChildRows("relation");
ds.Tables[index].Rows[index].GetParentRow("relation");
ds.Tables[index].Rows[index].GetParentRow("relation");

Orders

Customers
GetChildRows

DataSet

GetParentRow

Visually Navigating Between Tables Using


Relationships
Dim
Dim tableView
tableView As
As DataView
DataView
Dim
currentRowView
Dim currentRowView As
As DataRowView
DataRowView
tableView
tableView == New
New DataView(ds.Tables("Customers"))
DataView(ds.Tables("Customers"))
currentRowView
=
currentRowView = tableView(dgCustomers.SelectedIndex)
tableView(dgCustomers.SelectedIndex)
dgChild.DataSource
dgChild.DataSource == currentRowView.CreateChildView("CustOrders")
currentRowView.CreateChildView("CustOrders")
DataView
DataView tableView;
tableView;
DataRowView
DataRowView currentRowView;
currentRowView;
tableView
tableView == new
new DataView(ds.Tables["Customers"]);
DataView(ds.Tables["Customers"]);
currentRowView
currentRowView == tableView[dgCustomers.SelectedIndex];
tableView[dgCustomers.SelectedIndex];
dgChild.DataSource
dgChild.DataSource == currentRowView.CreateChildView("CustOrders");
currentRowView.CreateChildView("CustOrders");
Customers

DataView

DataRowView

CreateChildView

DataSet

Orders

Lesson: Accessing Data with DataReaders

What is a DataReader?

Creating a DataReader

Reading Data from a DataReader

Binding a DataReader to a List-Bound Control

Practice: Organizing Code to Create a DataReader

Demonstration: Displaying Data Using DataReaders

What is a DataReader?

Forward-only, read-only

Fast access to data

Connected to a data source

Manage the connection yourself

Manage the data yourself, or bind it to a list-bound


control

Uses fewer server resources

Creating a DataReader

To use a DataReader:
1.1

Create and open the database connection

2.2

Create a Command object

3.3

Create a DataReader from the Command object

4.4

44

Call the ExecuteReader method

55

Use the DataReader object

5.5

66

6.

77

7.

Close the DataReader object


Close the Connection object

Use TryCatchFinally error handling

Code Example

Reading Data from a DataReader

Call Read for each record

Returns false when there are no more records

Access fields
Parameter is the ordinal position or name of the field
Get functions give best performance

Do
Do While
While myReader.Read()
myReader.Read()
str
&=
str &= myReader(1)
myReader(1)
str
str &=
&= myReader("field")
myReader("field")
str
&=
myReader.GetDateTime(2)
str &= myReader.GetDateTime(2)
Loop
Loop

Close the DataReader

Close the connection

while
while (myReader.Read())
(myReader.Read())
{{
str
str +=
+= myReader[1];
myReader[1];
str
+=
myReader["field"];
str += myReader["field"];
str
str +=
+= myReader.GetDateTime(2);
myReader.GetDateTime(2);
}}

Binding a DataReader to a List-Bound Control

Create the Control

<asp:DataGrid
<asp:DataGrid id="dgAuthors"
id="dgAuthors" runat="server"
runat="server" />
/>

Bind to a DataReader

dgAuthors.DataSource
dgAuthors.DataSource == dr
dr
dgAuthors.DataBind()
dgAuthors.DataBind()

dgAuthors.DataSource
dgAuthors.DataSource == dr;
dr;
dgAuthors.DataBind();
dgAuthors.DataBind();

Using Parameters

Identify the available parameters

Input

Output

InputOutput

ReturnValue

Include parameters in the parameters collection


or

Include parameter values in the command string

Passing Input Parameters

Create parameter, set direction and value, add to the


Parameters collection
SqlParameter
param
SqlParameter
SqlParameter
param == new
new _
SqlParameter
param
=
New
SqlParameter
param
=
New
SqlParameter
_
("@Beginning_Date",
SqlDbType.DateTime);
("@Beginning_Date", SQLDbType.DateTime)
SqlDbType.DateTime);
("@Beginning_Date",
("@Beginning_Date",
SQLDbType.DateTime)
param.Direction
== ParameterDirection.Input;
param.Direction =
ParameterDirection.Input;
param.Direction
ParameterDirection.Input
param.Direction
=
ParameterDirection.Input
param.Value
== Convert.ToDateTime
param.Value =
Convert.ToDateTime
param.Value
param.Value = CDate(txtStartDate.Text)
CDate(txtStartDate.Text)
(txtStartDate.Text);
(txtStartDate.Text);
da.SelectCommand.Parameters.Add(param)
da.SelectCommand.Parameters.Add(param)
da.SelectCommand.Parameters.Add(param);
da.SelectCommand.Parameters.Add(param);

Run stored procedure and store returned records


DataSet()
ds
DataSet()
ds == New
New DataSet();
DataSet();
"Products")
da.Fill(ds,
"Products")
da.Fill(ds, "Products");
"Products");

Code Examples

Using Output Parameters

Create parameter, set direction, add to the Parameters


collection
param
param == New
New SqlParameter("@ItemCount",
SqlParameter("@ItemCount", SQLDbType.Int)
SQLDbType.Int)
param.Direction
param.Direction == ParameterDirection.Output
ParameterDirection.Output
da.SelectCommand.Parameters.Add(param)
da.SelectCommand.Parameters.Add(param)
param
param == new
new SqlParameter("@ItemCount",
SqlParameter("@ItemCount", SqlDbType.Int);
SqlDbType.Int);
param.Direction
param.Direction == ParameterDirection.Output;
ParameterDirection.Output;
da.SelectCommand.Parameters.Add(param);
da.SelectCommand.Parameters.Add(param);

Run stored procedure and store returned records


ds
ds == new
new DataSet()
DataSet()
da.Fill(ds)
da.Fill(ds)

ds
ds == new
new DataSet();
DataSet();
da.Fill(ds);
da.Fill(ds);

Read output parameters

iTotal
iTotal == da.Parameters("@ItemCount").Value
da.Parameters("@ItemCount").Value
iTotal
iTotal == da.Parameters("@ItemCount").Value;
da.Parameters("@ItemCount").Value;

THANK YOU

Das könnte Ihnen auch gefallen