Contents
Overview 1
Using ADO 2.5 2
Retrieving Data from a Database 10
Lab 7.1: Using ADO Commands Efficiently 16
Accessing Web Data 31
Lab 7.2: Accessing Data From a Web Site 44
Best Practices 47
Review 49
Module 7: Universal
Data Access with ADO
2.5
Information in this document is subject to change without notice. The names of companies,
products, people, characters, and/or data mentioned herein are fictitious and are in no way intended
to represent any real individual, company, product, or event, unless otherwise noted. Complying
with all applicable copyright laws is the responsibility of the user. No part of this document may
be reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose, without the express written permission of Microsoft Corporation. If, however, your only
means of access is electronic, permission to print one copy is hereby granted.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
2000 Microsoft Corporation. All rights reserved.
Microsoft, BackOffice, MS-DOS, Windows, Windows NT, Active Directory, ActiveX, FrontPage,
PowerPoint, Visual Basic, and Visual C++ are either registered trademarks or trademarks of
Microsoft Corporation in the U.S.A. and/or other countries.
The names of companies, products, people, characters, and/or data mentioned herein are fictitious
and are in no way intended to represent any real individual, company, product, or event, unless
otherwise noted.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Module 7: Universal Data Access with ADO 2.5 iii
Instructor Notes
This module describes how to use Microsoft ActiveX
®
Data Objects (ADO) 2.5
for universal data access. This material was prepared for students who already
know how to access relational data by using previous versions of ADO. The
module focuses on learning how to access databases efficiently in an enterprise
solution and how to access Web data by using the new ADO Record and
Stream objects introduced in Microsoft Windows 2000.
After completing this module, students will be able to:
!
Describe the major components of the ADO 2.5 object model.
!
Describe how to use ADO to access databases efficiently.
!
Use the Microsoft OLE DB Provider for Internet Publishing with ADO 2.5
to retrieve hierarchical data from a Web site.
!
Use the Recordset, Record, and Stream objects to access Web-based data.
In the first lab, students will learn how to use an ADO command object to make
efficient calls to a stored procedure. In the second lab, students will use the
Microsoft OLE DB Internet Publishing Provider and ADO 2.5 to retrieve
hierarchical data from a Web site. They will use a Recordset object to list the
documents in the Web site, a Record object to retrieve a specific document, and
a Stream object to preview the contents of a document.
Materials and Preparation
This section provides you with the required materials and preparation tasks that
are needed to teach this module.
Required Materials
To teach this module, you need the following materials:
!
Microsoft PowerPoint
®
file 1907A_07.ppt
!
Module 7: Universal Data Access with ADO 2.5
!
Lab 7.1: Using ADO Commands Efficiently
!
Lab 7.2: Accessing Data From a Web Site
Preparation Tasks
To prepare for this module, you should:
!
Read all of the materials for this module.
!
Complete the lab.
!
Read the instructor notes and margin notes for the module.
!
Practice the demonstrations and lab exercises.
Demonstration
This section provides demonstration procedures that will not fit in the margin
notes or are not appropriate for the student notes.
Presentation:
105 Minutes
Lab:
60 Minutes
iv Module 7: Universal Data Access with ADO 2.5
Using ADO to Access Web Data
!
Prepare for the demonstration
1. Use Windows Explorer to view the contents of the <install
folder>\Democode\Mod07 folder.
2. Right-click the Sales folder and choose Properties.
3. On the Web Sharing tab, click the Share this folder option button.
4. Leave the default alias (Sales) and ensure that all Access Permissions check
boxes are checked. Then click OK.
5. Click Yes to accept the warning message and then click OK on the
Properties dialog box.
!
Demonstrate opening records and recordsets
1. Open the Sales.vbp project in the <install folder>\Democode\Mod07 folder.
2. Display the variable declarations in the General Declarations section.
Explain that the objPendingFolder record object will represent the
PendingOrders folder in the Sales intranet, the objPending recordset object
will represent the contents of the PendingOrders folder, and that the
objOrder record object will represent the currently selected record in the
objPending recordset.
3. Display the code in the Form_Load event procedure.
Explain that the objPendingFolder record object is opened by using a
relative URL for the PendingOrders folder. The Absolute URL to the Sales
Web site is specified in the ConnectionString argument.
4. Display the ListOrders subprocedure.
Explain that this procedure opens the objPending recordset object by using
the GetChildren method of the objPendingOrders record object, and that
it loops through the records and adds the first field (the relative URL of the
record) to a list box.
5. Display the lstPendingOrders_Click() event procedure.
Explain that this code is used to synchronize the current record in the
objPending recordset with the currently selected item in the list box.
6. Run the project and note that it displays the three files in the PendingOrders
folder.
7. Stop the project.
!
Demonstrate file manipulation using the record object
1. Use Windows Explorer to show students the Sales Web folder hierarchy.
2. Display the code window for frmSales in the Sales.vbp project and show
the students the cmdLog_Click event procedure.
Explain that this code copies the currently selected file to the OrderLog
folder.
3. Display the cmdApprove_Click event procedure.
Explain that this code moves the currently selected file to the
ApprovedOrders folder.
Module 7: Universal Data Access with ADO 2.5 v
4. Display the cmdDelete_Click event procedure.
Explain that this code deletes the selected file.
5. Run the application and select Order1.xml.
6. Click Log.
7. Switch to Windows Explorer to show that the file has been copied to the
OrderLog folder.
8. Switch back to the running project and select Order2.xml.
9. Click Approve.
10. Switch to Windows Explorer to show that the file has been moved to the
ApprovedOrders folder.
11. Switch back to the running project and select Order3.xml.
12. Click Delete
13. Switch to Windows Explorer to show that the file has been deleted.
14. Stop the project.
!
Demonstrate file access using the Stream object
1. Display the code in the cmdPreview_Click event procedure.
Explain that this code opens the currently selected record from the
objPending recordset and then uses a stream object to open the contents of
the file for reading. The file is an ASCII text file and its contents are
displayed in a message box.
2. Run the project.
3. Select Order1.xml.
4. Click Preview to view the contents of the file.
5. Stop the project.
Module Strategy
Use the following strategy to present this module:
!
Using ADO 2.5
Discuss Microsoft’s data access strategy. Explain that ADO 2.5 is provided
with Microsoft Windows 2000 Server as part of the Microsoft Data Access
Components (MDAC). Discuss new ADO 2.5 features and review how to
use ADO to connect to a data source, retrieve selected data, and manipulate
data.
!
Retrieving Data from a Database
Explain that in an enterprise solution, it is critical that developers access
databases efficiently so that the maximum number of users can
simultaneously access the database with acceptable response times. Discuss
the importance of following recommended design guidelines and using
efficient data access programming techniques.
vi Module 7: Universal Data Access with ADO 2.5
Highlight some of the ways in which you can use ADO to access databases
efficiently, such as using the append technique to populate parameter
collections. Note the use of slide builds to explain ADO disconnected
recordsets. Use the builds to explain the process of opening, disconnecting,
reconnecting, and batch updating a recordset, as well as handling conflicts.
!
Accessing Web Data
Explain that many organizations are storing an increasing amount of data in
Web folders instead of in relational databases. Consequently, it is becoming
important to be able to access data from a Web site. Discuss that there is an
OLE DB provider for Internet Publishing that can be used with ADO 2.5 to
retrieve hierarchical data from a Web site.
Use the demonstration application to highlight each of the concepts covered.
You may choose to highlight these concepts incrementally as you discuss
each topic or to run the demonstration after all of the topics have been
taught.
!
Best Practices
Finish this module with a discussion of some of the best practices to follow
when using ADO 2.5 for Universal Data Access. Mention that the practical
implementation for most of these best practices was covered in various
sections throughout the module.
Module 7: Universal Data Access with ADO 2.5 1
#
##
#
Overview
!
Using ADO 2.5
!
Retrieving Data from a Database
!
Lab 7.1: Using ADO Commands Efficiently
!
Accessing Web Data
!
Lab 7.2: Accessing Data from a Web Site
!
Best Practices
!
Review
In this module, you will learn how learn how to use Microsoft
®
ActiveX
®
Data
Objects (ADO) 2.5 for Universal Data Access. This module was prepared for
students who already know how to access relational data by using previous
versions of ADO. As a result, you will focus on learning how to access
databases efficiently in an enterprise solution and how to access Web data by
using the new Record and Stream objects.
Objectives
After completing this module, you will be able to:
!
Describe the major components of the ADO 2.5 object model.
!
Describe how to use ADO to access databases efficiently.
!
Use Microsoft OLE DB Provider for Internet Publishing with ADO 2.5 to
retrieve hierarchical data from a Web site.
!
Use the Recordset, Record, and Stream objects to access Web-based data.
Slide Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
how to use ADO 2.5 for
Universal Data Access. You
will learn how to use the
OLE DB Provider for
Internet Publishing to
retrieve hierarchical data
from a Web site.
2 Module 7: Universal Data Access with ADO 2.5
#
##
#
Using ADO 2.5
!
Understanding OLE DB
!
The ADO 2.5 Object Model
!
Using ADO Objects
ADO 2.5 is provided with Microsoft Windows
®
2000 Server as part of the
Microsoft Data Access Components (MDAC).
In this section, you will learn about Microsoft’s data access strategy. You will
also learn how to use ADO 2.5 to connect to a data source, retrieve selected
data, and manipulate data.
This section includes the following topics:
!
Understanding OLE DB
!
The ADO 2.5 Object Model
!
Using ADO Objects
Module 7: Universal Data Access with ADO 2.5 3
Understanding OLE DB
Microsoft’s data access strategy is based on the OLE DB application
programming interface (API). OLE DB provides access to a diverse range of
data sources by using OLE DB providers. An OLE DB provider is a specialized
software driver, written for a specific data source, which enables the OLE DB
API to abstract the data source and present a standard programming interface to
client applications.
You can write code to directly manipulate the programming interface exposed
by OLE DB. However, this code can be complex and requires extensive low-
level knowledge of the OLE DB API. Alternatively, you can use the
Automation objects in the ADO 2.5 object library to access the OLE DB
interface and manipulate data. Using these objects provides a less complex
programming model and enables you to access data from compiled languages
such as Microsoft Visual Basic
®
and Microsoft Visual C++
®
, as well as from
interpreted languages such as Microsoft Visual Basic Scripting Edition or
Microsoft JScript
®
.
The following table shows some of the OLE DB providers available from
Microsoft and the data source with which they can be used.
Provider Data source Provider string
Microsoft OLE DB
provider for ODBC
Any ODBC compliant data
source
MSDASQL
Microsoft OLE DB
provider for Microsoft
Indexing Service
Microsoft Indexing
Service
MSIDXS
Microsoft OLE DB
provider for Microsoft
Active Directory
™
Service
Heterogeneous directory
services through ADSI
(including LDAP-
compliant directory
services and Novell NDS)
ADSDSOObject
4 Module 7: Universal Data Access with ADO 2.5
Provider Data source Provider string
OLE DB provider for
Microsoft Jet
Microsoft Jet databases,
such as those created with
Microsoft Access
Microsoft.Jet.OLEDB.4.0
Microsoft OLE DB
provider for SQL Server
™
Microsoft SQL Server
databases
SQLOLEDB
Microsoft OLE DB
provider for Oracle
Oracle databases MSDAORA
Microsoft OLE DB
provider for Internet
Publishing
Data published in IIS Web
sites or Windows 2000
Web folders
MSDAIPP.DSO
Microsoft OLE DB
provider for OLAP
Services
Multidimensional data in a
SQL Server OLAP
Services database
MSOLAP
Through these and other providers, you can use OLE DB and ADO to access
many different kinds of data throughout the enterprise.
The ADO library provides Automation objects, which allow diverse data
sources to be manipulated by using a standard set of properties and methods.
Depending on the provider being used, some ADO properties and methods may
produce inconsistent behavior or may not be supported.
Note
Module 7: Universal Data Access with ADO 2.5 5
The ADO 2.5 Object Model
Connection
Error
Property
Errors
Properties
Command
Parameters Parameter
Properties Property
Recordset
Fields Field
Properties Property
Record
Fields Field
Stream
The ADO 2.5 library provides five main objects that you can use to access data
programmatically through an OLE DB provider: the Connection, Command,
Recordset, Record, and Stream objects. In addition, the Connection object
contains a collection of Error objects, the Command object contains a
collection of Parameter objects, and the Recordset and Record objects each
contain a collection of Field objects. Finally, the Connection, Command, and
Recordset objects each contain a collection of Property objects.
The above illustration shows the relationship between the main ADO 2.5
objects and the collections of objects they contain.
In the rest of this section, you will learn more about the properties and methods
of each of the main objects in ADO 2.5. For more information about using
ADO, see the ADO documentation in the MSDN
™
Library.
6 Module 7: Universal Data Access with ADO 2.5
Using ADO Objects
!
Connection
$
Active session with a data source
!
Command
$
Command execution specific to data source
!
Recordset
$
Records returned from a data source
!
Record
$
An individual record or a resource in a file/Web hierarchy
!
Stream
$
Contents of a text or binary file
Each of objects in the ADO 2.5 library provides developers with methods and
properties that can be used to access and manipulate data. Most Visual Basic
6.0 developers will have used the Connection, Recordset, and Command
objects in previous versions of ADO. The addition of the Record and Stream
objects opens up new possibilities for accessing data in nonrelational data
sources.
Using the Connection Object
The Connection object represents a session with a data source. You can use the
collections, methods, and properties of the Connection object to perform a
wide variety of data access tasks, such as:
!
Specify a provider.
Use the ConnectionString property to specify a provider-specific
connection string.
!
Open the connection.
Use the Open method to open the connection.
!
Close the connection.
Use the Close method to close the connection.
!
Identify provider errors.
Use the Errors collection to identify errors specific to a data provider.
Module 7: Universal Data Access with ADO 2.5 7
Creating a Connection Object Explicitly
You can explicitly create instances of a Connection object by declaring a
variable of type ADODB.Connection, or implicitly by using the
ActiveConnection property of a Command or Recordset object. The
following code shows how to create a Connection object explicitly:
' Explicitly create a Connection object
Dim objCon As ADODB.Connection
Dim objRS As ADODB.Recordset
Dim strConnectionString As String
StrConnectionString =
"DSN=myODBCDSN;UID=graeme;PWD=topsecret;"
Set objCon = New ADODB.Connection
objCon.Open strConnectionString
Set objRS = New ADODB.Recordset
objRS.Open "SELECT * FROM Orders", objCon
Creating a Connection Object Implicitly
To create a Connection object implicitly, you can specify a connection string
for the ActiveConnection property of a Recordset or Command object, or
pass the connection details to the ActiveConnection parameter of the
Recordset object’s Open method. The following code shows how to create a
Connection object by using the Open method:
' Use an implicitly created Connection object
Dim objRS As ADODB.Recordset
Dim strConnectionString As String
StrConnectionString = _
"DSN=myODBCDSN;UID=graeme;PWD=topsecret;"
Set objRS = New ADODB.Recordset
objRS.Open "SELECT * FROM Orders", strConnectionString
' Connection is implicitly created and
' can be accessed using the
' objRS.ActiveConnection property
The Connection object has many other useful properties and methods, details
of which can be found in the Microsoft Data Access Components
documentation.
Using the Command Object
The Command object defines a specific command that you intend to execute
against a data source. Command objects can be used to retrieve data as a
recordset, update data, call a stored procedure, or execute an ad hoc command
by using syntax that is appropriate for the current provider by specifying
properties, collections, and methods:
!
CommandType property
The CommandType property of a Command object is used to specify the
kind of command to be executed. Constants that can be used for this
property include:
• adCmdTable for database tables
• adCmdStoredProc for database stored procedures
• adCmdText for provider specific command strings
8 Module 7: Universal Data Access with ADO 2.5
!
Parameters collection
The Parameters collection can be used to specify values for any input
parameters required by a command and also to retrieve output parameters
from stored procedures.
!
Execute method
After all the necessary properties have been set, the Execute method is used
to execute the command against the data source.
The following code shows how to use a Command object to update data in a
database:
Dim objCmd as ADODB.Command
Set objCmd = New ADODB.Command
With ObjCmd
.ActiveConnection = _
"DSN=myODBCDSN;UID=graeme;PWD=topsecret;"
.CommandText = _
"UPDATE orders SET status = 2 WHERE orderno = 1001"
.CommandType = adCmdText
.Execute
End With
Using the Recordset Object
The Recordset object represents the result of an executed command, usually a
set of records returned from a database query. Navigation through a recordset is
based on a record pointer or cursor. The cursor indicates which record in the
recordset is current. You can use the following properties to define a recordset:
!
CursorLocation property
The CursorLocation property of a Recordset object can be used to control
whether the cursor is hosted on the client application or on the server.
• adUseClient constant specifies the client application.
• adUseServer constant specifies the server.
!
CursorType property
The CursorType property can be used to specify the type of cursor created.
This property can be set to one of the following constants and should be
considered carefully because it can have a major effect on performance:
• adOpenStatic cursors must be located on the client and allow the
recordset to be navigated in any direction and updated. Users of a static
cursor will see their own changes, but changes made by other database
users will not be reflected.
• adOpenForwardOnly cursors are stored on the server and can only be
navigated in one direction.
• adOpenKeyset and adOpenDynamic cursors allow full navigation and
updating, and they are hosted on the server. Keyset and dynamic cursors
reflect updates and deletions made by other users; dynamic cursors also
reflect inserts made by other users. Although each cursor type can be
validly used in an appropriate situation, you should generally avoid
using dynamic and keyset cursors because they can incur overhead on
the database server.
Module 7: Universal Data Access with ADO 2.5 9
!
LockType property
The LockType property is used to manage concurrency issues by
controlling how the database locks records in a recordset for updating. This
property can be set to one of the following constants:
• adLockReadOnly prevents updates (and therefore update locks).
• adLockPessimistic locks records as soon as they are edited.
• adLockOptimistic locks records only after all edits have been
completed and the record is ready to be updated.
• adLockBatchOptimistic allows changes to be cached locally on the
client and sent as a batch by using the UpdateBatch method.
The following code shows how to open a recordset:
Set objRS = New ADODB.Recordset
With objRS
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.LockType = adLockReadOnly
End With
objRs.Open "SELECT * FROM sales", _
"DSN=myODBCDSN;UID=graeme;PWD=topsecret"
Using the Record Object
The Record object was added to the ADO library in version 2.5 and can
represent an individual row of a recordset or a resource (such as a file or
directory) in a file system. When combined with the OLE DB provider for
Internet Publishing, you can use the Record object to access hierarchical data in
a Web site such as Web pages or XML data.
Using the Stream Object
The Stream object was also added to the ADO library in version 2.5. It
represents a stream of binary data or text and is normally used with the Record
object to access the contents of a text or binary file.
For more information about using the Stream object, see Manipulating Web
Resources in this module.
10 Module 7: Universal Data Access with ADO 2.5
#
##
#
Retrieving Data from a Database
!
Using Connections Efficiently
!
Calling Stored Procedures
!
Using Disconnected Recordsets
!
Reconnecting and Batch Updating
!
Practice: Using Disconnected Recordsets
The most common use of ADO is to access and manipulate data in a relational
database such as Microsoft SQL Server. In an enterprise solution, it is critical
that you access databases efficiently so that the maximum number of users can
simultaneously access the database with acceptable response times. You can
make your solution perform and scale well with respect to database access by
following recommended design guidelines and by using efficient data access
programming techniques.
In this section, you will learn some of the ways you can use ADO to access
databases efficiently.
This section includes the following topics:
!
Using Connections Efficiently
!
Calling Stored Procedures
!
Using Disconnected Recordsets
!
Reconnecting and Batch Updating a Recordset
!
Practice: Using Disconnected Recordsets
Module 7: Universal Data Access with ADO 2.5 11
Using Connections Efficiently
!
COM+ component opens a database connection
!
When closed, the connection is placed in the pool
!
Pooled connections can be reused by other components
Maintaining multiple connections is a major overhead for a database server.
Each open connection uses a server license and requires memory to be set aside
for it. In a system with many users, this requirement can quickly overload a
server. One solution to this problem is to make sure that connections are closed
when not needed.
Using Database Connections in Client/Server
Applications
In a two-tier application, regularly closing and reopening connections to ease
the burden on the server can lead to performance issues at the client—
specifically, a slower response time. Opening connections is a resource-
consuming activity and in many two-tier applications, scalability is sacrificed
for response time and database connections are kept open, even when they are
not being used.
Using Database Connections in Multitier Applications
In an n-tier enterprise solution, you need to maximize scalability and still
provide acceptable client response time. One key enabling technology that
makes this objective possible is connection pooling for ODBC and OLE-DB
connections.
Connection pooling works by creating a pool of open connections on a per-
process basis. When code in a process explicitly closes a connection instead of
dropping the connection, it is placed in the pool to be reused by that process.
Because a COM+ application process (DLLHost.exe) can contain components
being used by multiple clients, the connections in the pool can be shared among
many users, thereby minimizing the impact on the server without frequently
closing and reopening connections.
12 Module 7: Universal Data Access with ADO 2.5
The following illustrations show how connection pooling can be used by a
COM+ application.
An object in the COM+ application uses a connection for database access.
The connection is closed and placed in the connection pool for this process.
Another object requires a database connection and uses the one in the pool.
When a process requires a database connection, it will look for an available
connection with matching security and data source configuration in the
connection pool. If no matching connection is found in the pool, a new database
connection is opened. Otherwise, an available connection in the pool is reused.
Taking Advantage of Connection Pooling
To take advantage of connection pooling, write code to open ADO connections
as late as possible and close them as early as possible. This approach allows the
connections to be recycled through the connection pool. Using explicit
connection objects rather than implicit connections may make coding easier,
although explicit connections are not a requirement for connection pooling.
Module 7: Universal Data Access with ADO 2.5 13
The following code shows how a connection can be quickly opened and closed
to execute a Command object against the database:
Dim objCon As ADODB.Connection
Dim objCmd As ADODB.Command
Set objCon = New ADODB.Connection
objCon.ConnectionString = STR_CONNECTION_STRING
Set objCmd = New ADODB.Command
objCmd.CommandText = strCommandText
objCon.Open 'Open connection to database
Set objCmd.ActiveConnection = objCon
objCmd.Execute
' Close connection and recycle it in the connection pool
objCon.Close
'...Further code for additional processing ...
Set objCmd = Nothing
Set objCon = Nothing
Another critical part of exploiting connection pooling is ensuring that the same
security credentials and connection information is used by as many data access
routines as possible. One way to accomplish this aim is to declare a constant
that defines the connection string to be used by all connections. Depending on
the security mode of the server, this constant may include login credentials. For
example, when accessing a SQL Server with the security mode set to standard
security, the following constant might be declared:
Const STR_CONNECTION_STRING = _
"DSN=OrdersDB;UID=OrderApp;PWD=topsecret;"
This connection would log the user, OrderApp, onto the database server by
using an ODBC data source named OrdersDB.
Alternatively, if the SQL Server were configured to support an integrated log
on, the user name and password could be omitted and the Windows account
used by the COM+ application would be used to authenticate the connection.
This configuration would ensure that all users access the database by using the
same user account and maximize the possibility of connections being reused.
Finally, when using connection pooling you need to remember that the
connection may be reused after you close it. Consequently, you should avoid
creating temporary database objects because they will remain in the database
server’s memory until the connection is finally released from the pool. You
should also avoid changing database context by using the USE
<databasename> SQL syntax because the original database connection may
need to be reused by another component instance.
To see a summary of best practices related to connection pooling, see Best
Practices in this module.
14 Module 7: Universal Data Access with ADO 2.5
Calling Stored Procedures
!
Using Commands with Parameters
$
Using the Refresh Method
$
Using the Append Method
objCmd.Parameters.Refresh
objCmd.Parameters(1).Value = lngOrderNumber
objCmd.Parameters.Append _
objCmd.CreateParameter(“OrderNo”, _
adInteger, _
4, _
adParamInput, _
lngOrderNumber)
You can use stored procedures on a database server to improve database
performance because procedures are compiled on first use and then the
compiled version is cached for subsequent executions. Stored procedures can be
executed by using the ADO Connection or Command objects and they can be
used to return records to a Recordset object.
Executing Commands with Parameters
When a stored procedure accepts parameters, you should use the Command
object to assign values to input parameters and retrieve data from output
parameters.
When using a Command object with parameters, there are two methods that
can be used to populate the Parameters collection: Refresh and Append.
Using the Refresh Method
You can use the Refresh method of the Parameters collection to initialize all
the parameters for the command. ADO initializes all of the parameters by
querying the data source for information about the parameters and default
values, so the ActiveConnection, CommandType, and CommandName
properties must all have been set before calling Refresh. The parameters then
simply need values assigned to them before being executed. If you fail to call
Refresh explicitly, it is called implicitly when you assign the first parameter
value. The following code shows how to use the Refresh method to populate
the Parameters collection of a Command object:
Module 7: Universal Data Access with ADO 2.5 15
Dim objCmd As ADODB.Command
Set objCmd = New ADODB.Command
With objCmd
Set .ActiveConnection = objCon
.CommandType = adCmdStoredProc
.CommandText = "UpdateOrderStatus"
.Parameters.Refresh 'Retrieve parameter info from server
.Parameters(1).Value = lngOrderNumber
.Parameters(2).Value = intNewStatus
.Execute Options:= adExecuteNoRecords
End With
Using the Append Method
The Refresh method is useful in situations in which the same Command object
will be used multiple times because it allows the parameters to be reinitialized
before each call. However, it requires an extra network trip to query the data
source for parameter information. In a COM+ application, where business
processes are designed to be self-contained and objects are generally stateless,
Command objects are not usually reused for multiple executions and this extra
network traffic is an unnecessary overhead.
To prevent the extra network trip, you can use the Append method of the
Parameters collection and the CreateParameter method of the Command
object to build the Parameters collection before connecting to the data source.
The CreateParameter method provides arguments to define parameter names,
data types, directions, sizes, and values.
The following code shows how to use the CreateParameter method as an
argument to the Append method:
objCmd.Parameters.Append objCmd.CreateParameter("OrderNo", _
adInteger, _
4, _
adParamInput, _
lngOrderNumber)
Alternatively, you can use a Parameter object as shown in the following code:
Dim prm as ADODB.Parameter
Set prm = objCmd.CreateParameter("StatusCode", _
adInteger, _
4, _
adParamInput, _
intNewStatus)
objCmd.Parameters.Append prm
16 Module 7: Universal Data Access with ADO 2.5
Lab 7.1: Using ADO Commands Efficiently
In this lab, you will use an ADO Command object to make efficient calls to a
stored procedure in the database.
Objectives
After completing this lab, you will be able to:
!
Use ADO Command objects to make efficient calls to parameterized stored
procedures.
Prerequisites
!
Before working on this lab, you should be familiar with the following:
!
ADO Command objects
!
Microsoft SQL Server stored procedures
Exercises
The following exercise provides practice in working with the concepts and
techniques covered in this module:
!
Exercise 1: Calling Parameterized Stored Procedures
In this exercise, you will modify the db_Order component so that it uses
ADO 2.5 command objects efficiently.
Estimated time to complete this lab: 20 minutes
Slide Objective
To introduce the lab.
Lead-in
In this lab, you will use an
ADO Command object to
make efficient calls to a
stored procedure in the
database.
Module 7: Universal Data Access with ADO 2.5 17
Exercise 1:
Calling Parameterized Stored Procedures
To complete the exercises in this lab, you must have the required software. For
detailed information about the labs and setup for the labs, see Labs in this In
this exercise, you will modify code in the db_Order component to use ADO 2.5
command objects efficiently.
!
View database activity when placing an order
In this procedure, you will use SQL Server Profiler to view database activity
when placing an order.
1. Start the SQL Server Profiler.
• On the Start menu, point to Programs, then point to the Microsoft
SQL Server 7.0 program group, and select Profiler.
2. If prompted to connect to a database server, connect to your local server and
select Use Windows NT authentication.
3. Click the Start Traces button on the toolbar and start the Sample 1 – TSQL
trace.
4. Minimize Profiler.
5. Open Microsoft Internet Explorer and navigate to
http://Localhost/POSystem/orderform.asp.
6. Add an item to the shopping cart and click Submit to place an order.
7. When the order is confirmed and an order number has been returned,
minimize Internet Explorer and maximize Profiler.
8. Note that Profiler has logged SQL Server activity.
In the trace recorded by Profiler, locate the RPC starting event for the
AddOrder stored procedure call. Note that this event is preceded by a call
to sp_ddopen, several calls to sp_cursorfetch, and a call to
sp_cursorclose. These calls are made by the ADO command object’s
Refresh method when initializing parameters.
9. Close Profiler and Internet Explorer.
!
Modify the ADO code used to call the AddOrder stored procedure
1. Start Microsoft Visual Basic.
2. Open the POData.vbp project in the <install folder>\Labs\Lab07\POData
folder.
3. Open the code window for the db_Order class and examine the code in the
Insert method.
4. Note that the code uses an ADO command object named cmd to call the
AddOrder stored procedure.
The AddOrder stored procedure has four parameters. The Refresh method
is not called explicitly, but it is called implicitly when the value of the first
parameter is set.
18 Module 7: Universal Data Access with ADO 2.5
5. Comment out the lines of code that set the Value and Direction properties
of the parameters.
6. Create the Parameters collection by adding the following line of code after
the lines you have commented out and before the call to the Execute
method:
.Parameters.Append .CreateParameter("UserID", _
adVarChar, _
adParamInput, _
40, _
strUserID)
7. Add code (after the line of code that you added in Step 6) to create the
remaining three parameters described in the following table.
Name Type Direction Size Value
CostCenter adVarChar adParamInput 20 strCostCenter
Total adCurrency adParamInput 4 curTotalValu
e
OrderNo adInteger adParamOutput 4 Not
applicable.
8. Locate the line of code "ordno = cmd.Parameters(4).Value" and change it to
the following:
ordno = cmd.Parameters("OrderNo").Value
9. Compile the POData.dll in <install folder>\Labs\Lab07\POData. You may
need to shut down the Purchase Order COM+ application to compile the
project.
• In the Component Services tool, right-click the Purchase Order
application and select Shut down.
10. Save your work and close Visual Basic.
!
Confirm the modifications to make the call more efficient
In this procedure, you will use SQL Server Profiler to confirm that Refresh is
no longer called.
1. Start the SQL Server Profiler.
• On the Start menu, point to Programs, then point to the Microsoft
SQL Server 7.0 program group, and select Profiler.
2. Click the Start Traces button on the toolbar and start the Sample 1 – TSQL
trace.
3. Minimize Profiler.
4. Open Internet Explorer and navigate to
http://Localhost/POSystem/orderform.asp.
5. Add an item to the shopping cart and click Submit to place an order.
6. When the order is confirmed and an order number has been returned,
minimize Internet Explorer and maximize Profiler.
Module 7: Universal Data Access with ADO 2.5 19
7. Note that Profiler has logged SQL Server activity.
• In the trace recorded by Profiler, locate the RPC starting event for the
AddOrder stored procedure call. Note that this call is no longer
preceded by a call to sp_ddOpen, several calls to sp_CursorFetch, and
a call to sp_CursorClose. By using the Append command to populate
the Parameters collection (as explained in the previous procedure), you
have made the call to the stored procedure more efficient.
8. Close Profiler and Internet Explorer.