0% found this document useful (0 votes)
7 views

Accessing Data With Visual Studio 2008

This document provides an overview of accessing data with Microsoft ADO.NET and Visual Studio 2008. It discusses what ADO.NET is, the ADO.NET object model including datasets and data readers, and how to connect to a database, access data, and access multiple tables. It describes generating connections through the Server Explorer, creating command objects, reading data with data readers, creating and populating datasets, binding data to controls, and handling errors.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Accessing Data With Visual Studio 2008

This document provides an overview of accessing data with Microsoft ADO.NET and Visual Studio 2008. It discusses what ADO.NET is, the ADO.NET object model including datasets and data readers, and how to connect to a database, access data, and access multiple tables. It describes generating connections through the Server Explorer, creating command objects, reading data with data readers, creating and populating datasets, binding data to controls, and handling errors.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 30

Accessing Data with

Microsoft ADO.NET and


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 provides:
• 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 from within
the .NET Framework
The ADO.NET Object Model

DataSet
DataTable
DataTable

SqlDataAdapter
OleDbDataAdapter

SQL Server .NET OLE DB .NET


Data Provider Data Provider
OleDbConnection
SqlConnection

SQL Server 7.0 OLEDB sources


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

DataSet DataReader

Read/write access to data Read-only

Includes multiple tables Based on one SQL statement


from 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
Manually coded
Studio 2008 tools
Accessing Data with ADO.NET

11
1. Client makes request
Database
222. Create the SqlConnection and SqlDataAdapter objects

3. Fill the DataSet from the DataAdapter and SqlConnection


33 Web
Webserver
server
close the connection
444. Return the DataSet to the Client SqlDataAdapter

5.
55 Client manipulates the data
6.
66 Update the DataSet
7.
77 Use the SqlDataAdapter to open
the SqlConnection, update the
database, and close the connection DataSet

List-Bound
List-Bound
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

• Create a new data • Create a new data


connection by dragging a connection by using
Table from Server Explorer Add Connection
The DataAdapter Object Model

DataSet
DataSet

DataAdapter
SelectCommand UpdateCommand InsertCommand DeleteCommand

DataReader
DataReader

Command
Command Command
Command Command
Command Command
Command

Connection
Connection

sp_SELECT sp_UPDATE sp_INSERT sp_DELETE


Database
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 ds As New DataSet()

DataSet ds = new DataSet();


• and then fill…

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

DataAdapter1.Fill(ds);
DataAdapter2.Fill(ds);
Creating a Connection Programmatically

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

string strConn = "data source=localhost; " +


"initial catalog=northwind; integrated security=true";
SqlConnection conn = new SqlConnection(strConn);

• Setting connection string parameters


 Connection timeout
 Password
 Data source  Persist security info
 Initial catalog  Provider
 Integrated security  User ID
Lesson: Accessing Data
• Accessing Data by Using the Visual Studio 2008 IDE

• Binding Data to Controls by Using the IDE

• Creating a Command Object

• Creating a Data Reader

• Retrieving Data by Using a DataReader

• Creating a DataSet Object

• Displaying a DataSet in a List-Bound Control

• Handling Errors
Accessing Data by Using the Visual Studio 2008 IDE

• Add a new database connection

• Specify the tables you want in the DataSet

• Save the connection string in the configuration file

• Specify a name for the DataSet


Bind 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
Creating a Command Object
• ExecuteReader. Returns a DataReader object

• ExecuteScalar. Returns a single scalar value

• ExecuteNonQuery. Executes a command that does not


return any rows
Creating a DataReader

• To create a DataReader:
1
1
1. Create and open the database connection
2
2
2. Create a Command object
3
3
3. Create a DataReader from the Command object
4
4
4. Call the ExecuteReader method
5
5
5. Use the DataReader object
6
6
6. Close the DataReader object
7
7.
7 Close the Connection object
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 While myReader.Read() while (myReader.Read())


str &= myReader(1) {
str &= myReader("field") str += myReader[1];
str &= str += myReader["field"];
myReader.GetDateTime(2) str +=
Loop myReader.GetDateTime(2);
}
• Close the DataReader

• Close the connection


Creating a DataSet

• Create and populate a DataSet with DataTables

 Fill method executes the SelectCommand

• Access a DataTable
Displaying DataSet Data in List-Bound Controls
• Set the properties

Property
Property Description
Description
DataSource
DataSource  The
TheDataSet
DataSetcontaining
containingthe
thedata
data
DataMember
DataMember  The
TheDataTable
DataTableininthe
theDataSet
DataSet
DataTextField
DataTextField  The
Thefield
fieldininthe
theDataTable
DataTablethatthatisisdisplayed
displayed
 The
Thefield
fieldininthe
theDataTable
DataTablethatthatbecomes
becomesthe the
DataValueField
DataValueField value
valueofofthe
theselected
selecteditem
itemininthe
thelist
list

• Fill the DataSet, then call the DataBind method

DataAdapter1.Fill(ds)
lstEmployees.DataBind()

DataAdapter1.Fill(ds)
lstEmployees.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: Accessing Multiple Tables
• Storing Data From Multiple Tables

• Creating Relationships

• Programmatically Navigating Between Tables Using


Relationships
Storing Data From Multiple Tables

• Add the first table


daCustomers = New SqlDataAdapter _
("select * from Customers", conn1)
daCustomers.Fill(ds, "Customers")
• Add the subsequent table(s)
daOrders = New SqlDataAdapter _
("select * from Orders", conn2)
daOrders.Fill(ds, "Orders")

Customers

conn1 conn2

DataSet Orders
Creating Relationships

• Identify parent column


parentCol Customers table DataRelation
• Identify child column
• Create DataRelation

childCol
DataSet Orders table
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

GetParentRow
DataSet
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_08
User name Student
Password Pa$$w0rd

Estimated time: xx minutes


Lab Scenario

Logon Page
Login.aspx
Benefits
Coho Home Page Page Header ASPState
Winery Default.aspx Header.ascx
Menu
Registration Component
Register.aspx Class1.vb or Class1.cs Web.
tempdb
config

Life Insurance Retirement Medical Dental


Life.aspx Retirement.aspx Medical.aspx Dental.aspx

Prospectus Doctors User Control XML Web


Lab Web Prospectus.aspx Doctors.aspx namedate.ascx Service
Application dentalService1.asmx

XML
Doctors Dentists
Files
Lab Review
Module Review and Takeaways
Review Questions
• How do you create a connection to a database?

• How do you create a DataSet?

• What is the code that is used to create a connection to a


database named Coho, on the local SQL Server, using
integrated security?
• What is the difference between a DataSet and a
DataReader object?
• How do you create a relationship between two DataTable
objects in a DataSet object?
Review for Alpha
• Is there any topic or specific content item in the module
that seemed unclear or unnecessary?
• Is there any content item/related subject area that was
not covered and could be included?
• Did you observe any issues with the technical accuracy of
the content?
• Is the content in the module presented in a manner that
encourages learning? Did the flow of topics seem right?
• Does the lab outline indicate the expected scope of tasks
to be covered? Would you like to suggest any tasks that
could be removed or added?

You might also like