You are on page 1of 28

Developing Web

Applications Using
Microsoft® Visual
Studio® 2008
Module 8: Accessing Data with Microsoft ADO.NET and
Visual Studio 2008
• Overview of ADO.NET

• Connecting to a Database

• Accessing Data

• Accessing Multiple Tables


Lesson: Overview of ADO.NET
• What Is ADO.NET?

• The ADO.NET Object Model

• DataSets and DataReaders

• Accessing Data with ADO.NET


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

• An evolutionary, more flexible successor to ADO

• 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 in
the .NET Framework
The ADO.NET Object Model
DataSet

DataTable DataTable

ODBC SQL Server OLE DB .NET Oracle


Data Provider Data Provider Data Provider Data Provider

ODBC SQL Server OLEDB sources Oracle


sources 7.0 (and later) (SQL Server 6.5) sources
DataSets and DataReaders

DataSet DataReader

Read/write access to data Read-only


Includes multiple tables from Based on one SQL statement
different databases from one database
Disconnected Connected

Bind to multiple controls Bind to one control only

Forward and backward


Forward-only
scanning of data

Slower access Faster access

Supported by Visual Studio


Manually coded
2008 Designer
Accessing Data with ADO.NET

Database
11 Client makes request

22 Create a SqlDataSource
Web
Web SqlDataSource
server
server
33 Return the data to the client

44 Client manipulates the data

55 Update the data

Use the SqlDataSource to open a


66 database connection, update the
database, and close the connection

GridView
GridView
Control
Control
Client
Client
Lesson: Connecting to a Database
• Generating a Connection by Using Server Explorer

• The DataAdapter Object Model

• Generating a DataSet

• Creating a Connection Programmatically


Generating a Connection by Using Server Explorer
• In Server Explorer, right-click Data Connections, and then
click Add Connection.
• Configure the connection
The DataAdapter Object Model
DataSet
DataSet

DataAdapter
SelectCommand UpdateCommand InsertCommand DeleteCommand

Command
Command Command
Command Command
Command Command
Command

Connection
Connection

SELECT UPDATE INSERT DELETE


Database
Generating a DataSet
• Creating a DataSet

[Visual C#] [Visual Basic]


DataSet myDataSet = Dim myDataSet As _
new DataSet(); New DataSet()

• Filling the DataSet

[Visual C#] [Visual Basic]


myDataAdapter1.Fill(ds); myDataAdapter1.Fill(ds)
myDataAdapter2.Fill(ds); myDataAdapter2.Fill(ds)
Creating a Connection Programmatically
• Creating a SqlConnection instance

[Visual C#]
string connectionString = "data source=localhost; " +
"initial catalog=northwind; integrated security=true";
SqlConnection connection = new SqlConnection(connectionString);

[Visual Basic]
Dim connectionString As String = "data source=localhost; " & _
"initial catalog=northwind; integrated security=true"
Dim connection As New SqlConnection(connectionString)
• Setting connection string parameters
 Connection timeout
 Data source
 Password
 Initial catalog
 Persist security info
 Integrated security
 Provider
 User ID
Lesson: Accessing Data
• Binding Data to Controls by Using the IDE

• Creating a Command Object

• Creating a DataReader

• Retrieving Data by Using a DataReader

• Creating a DataSet

• Displaying a DataSet in a List-Bound Control

• Handling Errors
Binding Data to Controls by Using the IDE
• Add a GridView control to the Web Form

• Bind the GridView control to a SqlDataSource control that


contains the connection and query information

• SqlDataSource properties:
 ConnectionString. The connection string to connect to the
database.
 ProviderName. The database type.

• GridView properties:
 Columns. The set of columns to be shown in the control
 DataSourceID. The control ID of a data source
Creating a Command Object
• ExecuteReader. Returns a DataReader object

• ExecuteScalar. Returns a single scalar value object

• ExecuteNonQuery. Executes a command that does not


return any rows
• ExecuteXmlReader. Returns an XmlReader object

[Visual C#]
myCommand.Connection.Open();
SqlDataReader myDataReader = myCommand.ExecuteReader();
// Process the results.
myCommand.Connection.Close();

[Visual Basic]
myCommand.Connection.Open()
Dim myDataReader As SqlDataReader = myCommand.ExecuteReader()
' Process the results.
myCommand.Connection.Close()
Creating a DataReader

11 Create and open the database connection

22 Create a Command object

33 Create a DataReader from the Command object

44 Call the ExecuteReader method

55 Use the DataReader object

66 Close the DataReader object

77 Close the Connection object


Retrieving Data by Using 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

[Visual C#] [Visual Basic]


while (myDataReader.Read()) { Do While myDataReader.Read()
text += myDataReader[1]; text &= myDataReader(1)
text += myDataReader["field"]; text &= myDataReader ("field")
text += text &=
myDataReader.GetDateTime(2); myDataReader.GetDateTime(2)
} Loop
• Close the DataReader

• Close the connection


Creating a DataSet
• Create and populate a DataSet with DataTable objects

 Fill method executes the SelectCommand

[Visual C#] [Visual Basic]


DataSet myDS = new DataSet(); Dim myDS As New DataSet()
myDA.Fill(myDataSet, myDA.Fill(myDataSet, _
"Authors"); "Authors")

• Access a DataTable

[Visual C#] [Visual Basic]


myDataSet.Tables[ myDS.Tables( _
"Authors"].Rows.Count; "Authors").Rows.Count
... ...
string text = ""; Dim row As DataRow
foreach(DataRow row in Dim text As String
myDS.Tables["Authors"].Rows) For Each row in
{ myDS.Tables("Authors").Rows
text += row[1]; text &= r(1)
text += row["LastName"]; text &= r("LastName")
} Next
Displaying DataSet Data in List-Bound Controls
• Set the properties

Property Description
DataSource The DataSet containing the data
DataMember The DataTable in the DataSet
The field in the DataTable that is
DataTextField
displayed
The field in the DataTable that becomes
DataValueField
the value of the selected item in the list

• Fill the DataSet, then call the DataBind method


[Visual C#] [Visual Basic]
myDataAdapter.Fill(myDataSet) myDataAdapter.Fill(myDataSet)
employeesList.DataBind(); employeesList.DataBind()
Handling Exceptions
• Connection will not open • DataAdapter cannot create
a DataSet
 Connection string is invalid
 Invalid SQL syntax
 Server or database not found
 Invalid table or field name
 Login failed

[Visual C#]
catch (System.Data.SqlClient.SqlException ex1)
[Visual
{ Basic]
Catch ex1 As System.Data.SqlClient.SqlException
switch(ex1.Number)
Select
{ Case ex1.Number
...
...
Case
case 18452
18452:
errorsLabel.Text
errorsLabel.Text =
= errorsLabel.Text
errorsLabel.Text &
+ _
("Invaliduser
("Invalid username");
name")
... break;
End Select
...
End Try
}
}
Lesson: Accessing Multiple Tables
• Storing Data From Multiple Tables

• Creating Relationships

• Programmatically Navigating Between Tables by


Using Relationships
Storing Data From Multiple Tables
• Add the first table

[Visual Basic]
C#]
customersDataAdapter = new SqlDataAdapter _
("select * from Customers", connection1)
connection1);
customersDataAdapter.Fill(myDataSet, "Customers")
"Customers");

• Add the subsequent table(s)


[Visual Basic]
C#]
ordersDataAdapter = new SqlDataAdapter _
("select * from Orders", connection2)
connection2);
customersDataAdapter.Fill(myDataSet, "Orders")
"Orders");

Customers
connection1 Orders
connection2

DataSet
Creating Relationships
• Identify parent column
parentColumn Customers table DataRelation
• Identify child column

• Create DataRelation

childColumn
DataSet Orders table

[Visual Basic]
C#]
Dim cORelation
DataRelation As DataRelation
coDataRelation;
Dim parentColumn
DataColumn As DataColumn,
parentColumn, childColumn As DataColumn
childColumn;

parentColumn = _
myDataSet.Tables("Customers").Columns("CustomerID")
myDataSet.Tables["Customers"].Columns["CustomerID"];
childColumn = _
myDataSet.Tables("Orders").Columns("CustomerID")
myDataSet.Tables["Orders"].Columns["CustomerID"];
cODataRelation = New
new DataRelation("CustomerOrders"
DataRelation("CustomerOrders",_
, parentColumn,
parentColumn, childColumn)
childColumn);
myDataSet.Relations.Add(cODataRelation)
myDataSet.Relations.Add(cODataRelation);
Programmatically Navigating Between Tables by
Using Relationships

[Visual Basic]
ds.Tables(index).Rows(index).GetChildRows("relation")
ds.Tables(index).Rows(index).GetParentRow("relation")

[Visual C#]
ds.Tables[index].Rows[index].GetChildRows("relation");
ds.Tables[index].Rows[index].GetParentRow("relation");

Customers Orders
GetChildRows

GetParentRow
DataSet
Lab: Accessing Data with Microsoft ADO.NET and
Visual Studio 2008
• Exercise 1: Connecting to the Doctors Database

• Exercise 2: Paging and Selection in a GridView Control

• Exercise 3: Implementing a SqlDataReader

• Exercise 4: (If Time Permits) Viewing Doctors from


All Cities

Logon information
Virtual machine 2310C-LON-DEV-08
User name Student
Password Pa$$w0rd

Estimated time: 45 minutes


Lab Scenario

Master Page
Logon Page benefitsMaster.master
login.aspx
Benefits Lab Web
Home Page Application
ASPState
Default.aspx Page Header
header.ascx
Menu Component
Registration Benefits.cs or Benefits.vb
register.aspx TempDB
Web.
config

Life Insurance Retirement Medical Dentists


life.aspx retirement.aspx medical.aspx dental.aspx

Prospectus
prospectus.aspx Doctors User Control XML Web
LINQ to SQL doctors.aspx nameDate.ascx Service
Classes DentalService1.asmx
Doctors.dbml

Doctors Dentists
XML Files
Lab Review
Review Questions
• How can you add a connection to a database?

• What controls are created when you drag a table from


Server Explorer to a Web page?
• How can you enable paging for a GridView control?

• How can you add a select column to a GridView control?

• When you use Connection and SqlDataReader objects,


what must you do?
Module Review and Takeaways
• Review Questions

• Real-World Issues and Scenarios

• Best Practices

You might also like