1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Module 7: Universal Data Access with ADO 2.5 docx

56 377 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Universal Data Access with ADO 2.5
Trường học Microsoft Corporation
Chuyên ngành Information Technology
Thể loại document
Năm xuất bản 2000
Định dạng
Số trang 56
Dung lượng 0,95 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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 Micr

Trang 1

Contents

Overview 1

Retrieving Data from a Database 10

Lab 7.1: Using ADO Commands Efficiently 16

Lab 7.2: Accessing Data From a Web Site 44

Review 49

Module 7: Universal Data Access with ADO 2.5

Trang 2

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

Trang 3

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

Trang 4

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

Trang 5

4 Display the cmdDelete_Click event procedure

Explain that this code deletes the selected file

5 Run the application and select Order1.xml

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

Trang 6

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

Trang 7

# 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

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

Trang 8

# 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

Trang 9

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 level knowledge of the OLE DB API Alternatively, you can use the

low-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

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

Heterogeneous directory services through ADSI (including LDAP-compliant directory services and Novell NDS)

ADSDSOObject

Trang 10

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

Microsoft SQL Server databases

SQLOLEDB

Microsoft OLE DB provider for Oracle

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

Note

Trang 11

The ADO 2.5 Object Model

Connection

Error

Property Errors

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

Trang 12

Using ADO Objects

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

Trang 13

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

Trang 14

! 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

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

Trang 15

! 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

Trang 16

# 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

Trang 17

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

resource-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 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

Trang 18

per-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

Trang 19

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

Trang 20

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:

Trang 21

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

Trang 22

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

Trang 23

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

Trang 24

5 Comment out the lines of code that set the Value and Direction properties

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

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

Trang 25

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

Trang 26

Using Disconnected Recordsets

GetRecords.Open “SELECT * FROM names”, con

End Function

As discussed earlier, one way to improve scalability in an enterprise application

is to close connections as quickly as possible However, some business processes may involve long operations with recordsets Because connections generally should not be held open, you should consider disconnecting recordsets that will be required for lengthy periods of time and reconnecting them later to update data on the server if necessary

Preparing a Recordset to Be Disconnected

To be able to disconnect a recordset, you must first set the following properties:

! Set CursorLocation to adUseClient

! Set CursorType to adOpenStatic (This property is set implicitly when

CursorLocation is set to adUseClient.)

! Set LockType to adLockBatchOptimistic so that batch updates can be

performed

After these properties have been set, an additional property named Update

Criteria may be set that controls how conflicts are handled when changes in the

recordset are sent to the server Because the Update Criteria property is nonstandard, you must set this property by using the Properties collection with

the following syntax:

<RecordsetVariable>.Properties("Update Criteria") =

<UpdateCriteriaConstant>

Trang 27

You can set the UpdateCriteriaConstant parameter to any of four constants:

! adCriteriaUpdCols

Conflicts occur if the same column has been changed on both the server and the disconnected client For example, if a disconnected recordset contains FirstName and LastName columns and the FirstName column of a record is

updated, then a conflict will occur if another user has updated the FirstName

column on the server for the same record, but no conflict will occur if only the LastName column on the server has been updated This setting is the default

! adCriteriaAllCols

Conflicts occur when changes are made to any column on both the server and the disconnected client For example, if a disconnected recordset contains FirstName and LastName columns and the FirstName column of a record is updated, a conflict will occur if another user has updated the

FirstName or LastName column on the server for the same record

! adCriteriaKey

Conflicts only occur if the key value is changed on both the server and client The key value is changed on both the server and client when another user has deleted the record

! adCriteriaTimeStamp

A TimeStamp column will be used to detect conflicts Conflicts occur when

the row has been accessed after the Recordset was obtained

Disconnecting a Recordset

After all the appropriate properties are set, the recordset can be opened and

disconnected from the server by setting the ActiveConnection property to

Nothing When a recordset has been disconnected, it can be navigated and updated just like any other recordset In a COM+ component, you can create a method to retrieve data in a recordset, disconnect the recordset, and marshal the entire recordset to the calling client application, as shown in the following code: Public Function RetrieveOrders() As ADODB.Recordset

Set RetrieveOrders = New ADODB.Recordset With RetrieveOrders

CursorLocation = adUseClient .CursorType = adOpenStatic .LockType = adLockBatchOptimistic End With

objCon.Open RetrieveOrders.Open "SELECT * FROM Orders", objCon Set RetrieveOrders.ActiveConnection = Nothing GetObjectContext.SetComplete

End Function

Trang 28

This method could be called from a client application, as shown in the following code:

Dim objRS As ADODB.Recordset Dim objBusOrders As OrderSystem.OrderList 'COM+ Component Set objRS = objBusOrder.RetrieveOrders

Each field in a disconnected recordset has three properties that relate to the value of the field:

This property represents the value of the field in the database on the server

It is usually used when the recordset is reconnected and conflicts have occurred

Initially, all three properties will have the same value

Using a Disconnected Recordset Offline

After disconnecting a recordset, you can work with it just as you would any

other recordset All Update, AddNew, and Delete operations can be applied to

the disconnected recordset without any need for a connection to the server

On the client, the disconnected recordset can be stored to disk by using the

Save method and closed if necessary The Save method takes two parameters:

filename (including path) and fileformat You can save ADO recordsets in a

binary format by using the adPersistATG constant, or as an Extensible Markup Language (XML) stream by using the adPersistXML constant You can then use the Open method to reopen the recordset from a file You will set the

Source argument to the filename including its path and the Options argument

to adCmdFile The following code shows how to save, close, and reopen a

Ngày đăng: 21/12/2013, 19:15

TỪ KHÓA LIÊN QUAN