View
237
Download
2
Category
Tags:
Preview:
DESCRIPTION
dsss
Citation preview
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
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
What is ADO.NET?
Using Namespaces
Use the Imports or using statement to import namespaces
Namespaces used with ADO.NET include:
System.Data
System.Data.SqlClient
System.Data.OleDb
Imports System.DataImports System.Data.SqlClientImports System.DataImports System.Data.SqlClient
using System.Data;using System.Data.SqlClient;using System.Data;using System.Data.SqlClient;
DataSet
SQL Server .NET Data Provider
OLE DB .NET Data Provider
SQL Server 7.0(and later)
OLEDB sources(SQL Server 6.5)
OleDbConnectionOleDbConnection
OleDbDataAdapterOleDbDataAdapterSqlDataAdapterSqlDataAdapter
SqlConnectionSqlConnection
DataTable
DataTable
The ADO.NET Object Model
SQL Server 2000
DataSet
DataTable
DataTable
Physical storage
OleDb Database
SqlDataAdapterSqlDataAdapter
SqlConnectionSqlConnection
DataTable
Web server memory
OleDbDataAdapterOleDbDataAdapter
OleDbConnection
OleDbConnection
What is a Dataset?
Accessing Data with ADO.NET
DatabaseDatabase
4. Return the DataSet to the Client
5. Client manipulates the data
2. Create the SqlConnection and SqlDataAdapter objects
3. Fill the DataSet from the DataAdapter and close the connection
SqlDataAdapter
SqlConnection
List-Bound
Control
List-Bound
Control
1. Client makes request1111
2222
3333
4444
5555
6. Update the DataSet
7. Use the SqlDataAdapter to open the SqlConnection, update the database, and close the connection
6666
7777
ClientClient
Web serverWeb server
DataSet
The DataAdapter Object Model
sp_SELECT
CommandCommand
SelectCommand UpdateCommand InsertCommand DeleteCommand
DataAdapter
CommandCommand CommandCommand CommandCommand
ConnectionConnection
sp_UPDATE sp_INSERT sp_DELETE
Database
DataSetDataSet
DataReaderDataReader
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…
and then fill…
Dim ds As New DataSet()Dim ds As New DataSet()
DataAdapter1.Fill(ds)DataAdapter2.Fill(ds)DataAdapter1.Fill(ds)DataAdapter2.Fill(ds)
DataSet ds = new DataSet();DataSet ds = new DataSet();
DataAdapter1.Fill(ds);DataAdapter2.Fill(ds);DataAdapter1.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
ListBox
CheckBoxList
RadioButtonList
DataGrid
DataList
Repeater
Displaying DataSet Data in List-Bound Controls
Set the properties
Fill the DataSet, then call the DataBind methodDataAdapter1.Fill(ds)lstEmployees.DataBind()DataAdapter1.Fill(ds)lstEmployees.DataBind()
PropertyPropertyPropertyProperty DescriptionDescriptionDescriptionDescription
DataSourceDataSource The DataSet containing the data The DataSet containing the data
DataMemberDataMember The DataTable in the DataSet The DataTable in the DataSet
DataTextFieldDataTextField The field in the DataTable that is displayed The field in the DataTable that is displayed
DataValueFieldDataValueField The field in the DataTable that becomes the value of the selected item in the list
The field in the DataTable that becomes the value of the selected item in the list
DataAdapter1.Fill(ds);lstEmployees.DataBind();DataAdapter1.Fill(ds);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
Slower access
Forward-only
Bind to one control only
Based on one SQL statement from one database
Read-only
Faster access
Forward and backward scanning of data
Bind to multiple controls
Includes multiple tables from different databases
Read/write access to data
DataReaderDataSet
Disconnected Connected
Lesson: Connecting to a Database
SQL Server Security
Creating the Connection
Demonstration: Setting SQL Server Security
SQL Server Security
ClientClient
Send the username and password in
clear text.
Do not send the username and
password. Just send that the user has been authenticated.
Mixed modeauthenticationMixed mode
authentication
Windows onlyauthenticationWindows onlyauthentication
SQL ServerOnly ASPNET account
is granted access
SQL ServerOnly ASPNET account
is granted accessWeb ServerWindows authentication
Web ServerWindows authentication
or…or…
SQL ServerEach user account added
to SQL Server logins group
SQL ServerEach user account added
to SQL Server logins group
Web ServerDefault ASP.NET settings
Web ServerDefault ASP.NET settings
Here is the username and
password
Creating the Connection
Using SqlConnection
Setting connection string parameters
Data Base
Server
User ID
Dim con as new connection()Con.connectionstring=“database=master;server=ORION;Uid=sample;pwd=sample;”Con.open()
Dim con as new connection()Con.connectionstring=“database=master;server=ORION;Uid=sample;pwd=sample;”Con.open()
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
Store the query in a DataAdapter
The DataAdapter constructor sets the SelectCommand property
Set the InsertCommand, UpdateCommand, and DeleteCommand properties if needed
Creating a DataAdapter
Dim da As New SqlDataAdapter ("select * from Authors", conn)
Dim da As New SqlDataAdapter ("select * from Authors", conn)
da.SelectCommand.CommandText da.SelectCommand.Connection
da.SelectCommand.CommandText da.SelectCommand.Connection
SqlDataAdapter da = new SqlDataAdapter("select * from Authors",conn);
SqlDataAdapter da = new SqlDataAdapter("select * from Authors",conn);
da.SelectCommand.CommandText;da.SelectCommand.Connection;
da.SelectCommand.CommandText;da.SelectCommand.Connection;
Creating a DataSet
Create and populate a DataSet with DataTables
Fill method executes the SelectCommand
Access a DataTable
Dim ds As New DataSet()da.Fill(ds, "Authors")
Dim ds As New DataSet()da.Fill(ds, "Authors")
Dim r As DataRowDim str As StringFor Each r in _ ds.Tables("Authors").Rows str &= r(2) str &= r("au_lname")Next
Dim r As DataRowDim str As StringFor Each r in _ ds.Tables("Authors").Rows str &= r(2) str &= r("au_lname")Next
ds.Tables("Authors").Rows.Countds.Tables("Authors").Rows.Count
DataSet ds = new DataSet();da.Fill(ds, "Authors");
DataSet ds = new DataSet();da.Fill(ds, "Authors");
ds.Tables["Authors"].Rows.Count;ds.Tables["Authors"].Rows.Count;
string str="";
foreach(DataRow r in ds.Tables["Authors"].Rows){ str += r[2]; str += r["au_lname"];}
string str="";
foreach(DataRow r in ds.Tables["Authors"].Rows){ str += r[2]; str += r["au_lname"];}
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
Setting up a different view of a DataSet
DataView dv = new DataView(ds.Tables["Authors"]);dv.RowFilter = "state = 'CA'";
DataView dv = new DataView(ds.Tables["Authors"]);dv.RowFilter = "state = 'CA'";
Dim dv As DataView = ds.Tables("Authors").DefaultView Dim dv As DataView = ds.Tables("Authors").DefaultView
Dim dv As New DataView (ds.Tables("Authors"))dv.RowFilter = "state = 'CA'"
Dim dv As New DataView (ds.Tables("Authors"))dv.RowFilter = "state = 'CA'"
DataView dv = ds.Tables["Authors"].DefaultView;DataView dv = ds.Tables["Authors"].DefaultView;
Binding a DataSet to a List-Bound Control
Create the control
Bind to a DataSet or a DataView
dg.DataSource = dsdg.DataMember = "Authors"dg.DataBind()
dg.DataSource = dsdg.DataMember = "Authors"dg.DataBind()
<asp:DataGrid id="dg" runat="server" /><asp:DataGrid id="dg" runat="server" />
dg.DataSource = ds;dg.DataMember = "Authors";dg.DataBind();
dg.DataSource = ds;dg.DataMember = "Authors";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
Add the subsequent table(s)
daCustomers = New SqlDataAdapter _ ("select * from Customers", conn1)daCustomers.Fill(ds, "Customers")
daCustomers = New SqlDataAdapter _ ("select * from Customers", conn1)daCustomers.Fill(ds, "Customers")
Orders
Customers
daOrders = New SqlDataAdapter _ ("select * from Orders", conn2)daOrders.Fill(ds, "Orders")
daOrders = New SqlDataAdapter _ ("select * from Orders", conn2)daOrders.Fill(ds, "Orders")
conn2conn1
DataSet
Creating Relationships
Identify parent column
Identify child column
Create DataRelation
Dim dr As New DataRelation _ ("name", parentCol, _ childCol)ds.DataRelations.Add(dr)
Dim dr As New DataRelation _ ("name", parentCol, _ childCol)ds.DataRelations.Add(dr)
Dim parentCol As DataColumn = _ ds.Tables("Customers").Columns("CustomerID")
Dim parentCol As DataColumn = _ ds.Tables("Customers").Columns("CustomerID")
Dim childCol As DataColumn = _ ds.Tables("Orders").Columns("CustomerID")
Dim childCol As DataColumn = _ ds.Tables("Orders").Columns("CustomerID")
Orders table
Customers table
DataSet
parentCol
childCol
DataRelation
Programmatically Navigating Between Tables Using Relationships
ds.Tables(index).Rows(index).GetChildRows("relation")ds.Tables(index).Rows(index).GetParentRow("relation")
ds.Tables(index).Rows(index).GetChildRows("relation")ds.Tables(index).Rows(index).GetParentRow("relation")
Customers Orders
GetChildRows
GetParentRowDataSet
ds.Tables[index].Rows[index].GetChildRows("relation");ds.Tables[index].Rows[index].GetParentRow("relation");
ds.Tables[index].Rows[index].GetChildRows("relation");ds.Tables[index].Rows[index].GetParentRow("relation");
Visually Navigating Between Tables Using Relationships
Dim tableView As DataViewDim currentRowView As DataRowView
tableView = New DataView(ds.Tables("Customers"))currentRowView = tableView(dgCustomers.SelectedIndex)dgChild.DataSource = currentRowView.CreateChildView("CustOrders")
Dim tableView As DataViewDim currentRowView As DataRowView
tableView = New DataView(ds.Tables("Customers"))currentRowView = tableView(dgCustomers.SelectedIndex)dgChild.DataSource = currentRowView.CreateChildView("CustOrders")
Customers Orders
CreateChildView
DataRowView
DataView
DataSet
DataView tableView;DataRowView currentRowView;
tableView = new DataView(ds.Tables["Customers"]);currentRowView = tableView[dgCustomers.SelectedIndex];dgChild.DataSource = currentRowView.CreateChildView("CustOrders");
DataView tableView;DataRowView currentRowView;
tableView = new DataView(ds.Tables["Customers"]);currentRowView = tableView[dgCustomers.SelectedIndex];dgChild.DataSource = currentRowView.CreateChildView("CustOrders");
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
Code Example
Creating a DataReader
To use a DataReader:
1. Create and open the database connection
2. Create a Command object
3. Create a DataReader from the Command object
4. Call the ExecuteReader method
5. Use the DataReader object
6. Close the DataReader object
7. Close the Connection object Use Try…Catch…Finally error handling
1111
2222
3333
4444
5555
6666
7777
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
Close the DataReader
Close the connection
Do While myReader.Read() str &= myReader(1) str &= myReader("field") str &= myReader.GetDateTime(2)Loop
Do While myReader.Read() str &= myReader(1) str &= myReader("field") str &= myReader.GetDateTime(2)Loop
while (myReader.Read()){ str += myReader[1]; str += myReader["field"]; str += myReader.GetDateTime(2);}
while (myReader.Read()){ str += myReader[1]; str += myReader["field"]; str += myReader.GetDateTime(2);}
Binding a DataReader to a List-Bound Control
Create the Control
Bind to a DataReader
dgAuthors.DataSource = drdgAuthors.DataBind()
dgAuthors.DataSource = drdgAuthors.DataBind()
<asp:DataGrid id="dgAuthors" runat="server" /><asp:DataGrid id="dgAuthors" runat="server" />
dgAuthors.DataSource = dr;dgAuthors.DataBind();
dgAuthors.DataSource = dr;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
Run stored procedure and store returned records
SqlParameter param = new SqlParameter ("@Beginning_Date", SqlDbType.DateTime);param.Direction = ParameterDirection.Input;param.Value = Convert.ToDateTime
(txtStartDate.Text);da.SelectCommand.Parameters.Add(param);
SqlParameter param = new SqlParameter ("@Beginning_Date", SqlDbType.DateTime);param.Direction = ParameterDirection.Input;param.Value = Convert.ToDateTime
(txtStartDate.Text);da.SelectCommand.Parameters.Add(param);
ds = New DataSet();da.Fill(ds, "Products");
ds = New DataSet();da.Fill(ds, "Products");
Code Examples
ds = New DataSet()da.Fill(ds, "Products")
ds = New DataSet()da.Fill(ds, "Products")
param = New SqlParameter _ ("@Beginning_Date", SQLDbType.DateTime)param.Direction = ParameterDirection.Inputparam.Value = CDate(txtStartDate.Text)da.SelectCommand.Parameters.Add(param)
param = New SqlParameter _ ("@Beginning_Date", SQLDbType.DateTime)param.Direction = ParameterDirection.Inputparam.Value = CDate(txtStartDate.Text)da.SelectCommand.Parameters.Add(param)
Using Output Parameters
Create parameter, set direction, add to the Parameters collection
Run stored procedure and store returned records
Read output parameters
param = New SqlParameter("@ItemCount", SQLDbType.Int)param.Direction = ParameterDirection.Outputda.SelectCommand.Parameters.Add(param)
param = New SqlParameter("@ItemCount", SQLDbType.Int)param.Direction = ParameterDirection.Outputda.SelectCommand.Parameters.Add(param)
ds = new DataSet()da.Fill(ds)
ds = new DataSet()da.Fill(ds)
iTotal = da.Parameters("@ItemCount").Value iTotal = da.Parameters("@ItemCount").Value
param = new SqlParameter("@ItemCount", SqlDbType.Int);param.Direction = ParameterDirection.Output;da.SelectCommand.Parameters.Add(param);
param = new SqlParameter("@ItemCount", SqlDbType.Int);param.Direction = ParameterDirection.Output;da.SelectCommand.Parameters.Add(param);
ds = new DataSet();da.Fill(ds);
ds = new DataSet();da.Fill(ds);
iTotal = da.Parameters("@ItemCount").Value; iTotal = da.Parameters("@ItemCount").Value;
THANK YOU
Recommended