2310 b 10

34
Module 10: Accessing Data with Microsoft ADO.NET

Transcript of 2310 b 10

Page 1: 2310 b 10

Module 10: Accessing Data with Microsoft ADO.NET

Page 2: 2310 b 10

Overview

Introduction to Using ADO.NET

Connecting to a Database

Accessing Data with DataSets

Using Multiple Tables

Accessing Data with DataReaders

Page 3: 2310 b 10

Lesson: Introduction to Using ADO.NET

Multimedia: The ADO.NET Object Model

Using DataSets vs. DataReaders

Practice: When to Use DataSets or DataReaders

Page 4: 2310 b 10

Multimedia: The ADO.NET Object Model

Page 5: 2310 b 10

Using DataSets vs. DataReaders

Supported by Visual Studio .NET tools

Slower access

Forward-only

Bind to one control only

Based on one SQL statement from one database

Read-only

Manually coded

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

Page 6: 2310 b 10

Practice: When to Use DataSets or DataReaders

Students will:

Select the best data access choice for given scenarios

Time: 5 Minutes

Page 7: 2310 b 10

Lesson: Connecting to a Database

SQL Server Security

Creating the Connection

Demonstration: Setting SQL Server Security

Page 8: 2310 b 10

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

Page 9: 2310 b 10

Creating the Connection

Using SqlConnection

Setting connection string parameters

Connection timeout

Data source

Initial catalog

Integrated security

Dim strConn As String = "data source=localhost; " & _ "initial catalog=northwind; integrated security=true"Dim conn As New SqlConnection(strConn)

Dim strConn As String = "data source=localhost; " & _ "initial catalog=northwind; integrated security=true"Dim conn As New SqlConnection(strConn)

Password

Persist security info

Provider

User ID

string strConn = "data source=localhost; " + "initial catalog=northwind; integrated security=true";SqlConnection conn = new SqlConnection(strConn);

string strConn = "data source=localhost; " + "initial catalog=northwind; integrated security=true";SqlConnection conn = new SqlConnection(strConn);

Page 10: 2310 b 10

Demonstration: Setting SQL Server Security

Open SQL Server Enterprise Manager

Set authentication mode

Test with integrated security

Test with mixed mode security

Page 11: 2310 b 10

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

Page 12: 2310 b 10

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;

Page 13: 2310 b 10

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"];}

Page 14: 2310 b 10

Demonstration: Programmatically Using a DataSet

Create a Connection

Create DataAdapter

Create DataSet

Read data from DataSet programmatically

Page 15: 2310 b 10

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;

Page 16: 2310 b 10

Practice: Organizing Code to Create a DataSet

Student will:

Reorder lines of code to create a DataSet

Time: 5 Minutes

Page 17: 2310 b 10

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();

Page 18: 2310 b 10

Instructor-Led Practice: Displaying a DataSet

Create a Connection

Create a DataAdapter

Create a DataSet

Create a DataView

Bind both the DataSet and DataView to DataGrid controls

Page 19: 2310 b 10

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

Page 20: 2310 b 10

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

Page 21: 2310 b 10

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

Page 22: 2310 b 10

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

C# Code Example

Page 23: 2310 b 10

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");

Page 24: 2310 b 10

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");

Page 25: 2310 b 10

Instructor-Led Practice: Displaying Data from Multiple Tables

Programmatically:

Create a DataSet

Create a DataRelation

Display child records using the DataRelation

Visually:

Call CreateChildView

Page 26: 2310 b 10

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

Page 27: 2310 b 10

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

Page 28: 2310 b 10

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

Page 29: 2310 b 10

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);}

Page 30: 2310 b 10

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();

Page 31: 2310 b 10

Practice: Organizing Code to Create a DataReader

Students will:

Reorder lines of code to create a DataReader

Time: 5 Minutes

Page 32: 2310 b 10

Demonstration: Displaying Data Using DataReaders

Create a SqlConnection

Create a DataReader

Bind the DataReader to a ListBox

Build ListBox items from data supplied by the DataReader

Page 33: 2310 b 10

Review

Introduction to Using ADO.NET

Connecting to a Database

Accessing Data with DataSets

Using Multiple Tables

Accessing Data with DataReaders

Page 34: 2310 b 10

MedicalMedical.aspxMedicalMedical.aspx

Lab 10: Accessing Data with Microsoft ADO.NET

BenefitsHome PageDefault.aspx

BenefitsHome PageDefault.aspx

Life InsuranceLife.aspxLife InsuranceLife.aspx

RetirementRetirement.aspxRetirementRetirement.aspx

DentalDental.aspxDentalDental.aspx

Dentists

DoctorsDoctors.aspx DoctorsDoctors.aspx

Doctors

Logon PageLogin.aspxLogon PageLogin.aspx

RegistrationRegister.aspxRegistrationRegister.aspx

CohoWinery

ProspectusProspectus.aspxProspectusProspectus.aspx

XML Web ServicedentalService1.asmx

XML Web ServicedentalService1.asmx

Page HeaderHeader.ascxPage HeaderHeader.ascx

ASPState

tempdb

Lab Web Application

User Controlnamedate.ascxUser Controlnamedate.ascx

Menu ComponentClass1.vb or Class1.cs

Menu ComponentClass1.vb or Class1.cs

XML Files

Web.config