Updating Data in an ADO Data Source 28 Accessing Exchange Server Information 37 Lab A: Searching and Retrieving Information in the Exchange Server Directory by Using ADSI 54 Review 5
Trang 1Updating Data in an ADO Data Source 28
Accessing Exchange Server Information 37
Lab A: Searching and Retrieving
Information in the Exchange Server
Directory by Using ADSI 54
Review 57
Module 11: Accessing Data from the
Outlook 2000 Client
Trang 2to 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
1999 Microsoft Corporation All rights reserved
Microsoft, Active Desktop, Active Directory, ActiveX, BackOffice, Developer Studio, FrontPage, JScript, MSDN, MSN, NetMeeting, Outlook, PivotChart, PivotTable, PowerPoint, Visual Basic, Visual C++, Visual FoxPro, Visual InterDev, Visual J++, Visual SourceSafe, Visual Studio, Windows, Windows Media, and Windows NT 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
Project Advisor: Janet Wilson
Project Lead and Instructional Designer: Anne Bockman (Excell Data Corporation)
Instructional Designers: Josh Barnhill (Volt Technical) and Jo Berry (Exchange)
Lead Program Manager: Greg Bott
Program Managers: Colleena Carr and Chris Boar (Intl Vendor)
Graphic Artist: Andrea Heuston (Artitudes Layout and Design)
Editing Manager: Lynette Skinner
Editor: Jennifer Kerns (S&T Onsite)
Copy Editor: Shari G Smith (R & S Consulting)
Online Program Manager: Arlo Emerson (Aditi)
Production Support: Irene Barnett (Barnett Communications)
Manufacturing Manager: Bo Galford
Manufacturing Support: Mimi Dukes (S&T Onsite)
Development Services: Kimber Dodge
Lead Product Manager: Mary Larson
Group Product Manager: Robert Stewart
Trang 3Instructor Notes Module 11: Accessing Data from the
in the Microsoft Exchange Server directory by using the Outlook object model, Collaborative Data Objects (CDO), and Microsoft Active Directory™ Service
Interfaces (ADSI)
Materials and Preparation
This section provides you with the materials and preparation needed to teach this module
Materials
To teach this module, you need the following materials:
Microsoft PowerPoint® file 1593a_11.ppt
Module 11, “Accessing Data from the Outlook 2000 Client”
Preparation
To prepare for this module, you should:
Read all the materials for this module
Read the instructor notes and margin notes for the module
Complete the lab
Rehearse the demonstration
Presentation:
60 Minutes
Lab:
45 Minutes
Trang 4Module Strategy
Use the following strategy to present this module:
Introduction to Data Access in Outlook 2000 Solutions Describe the different ways that SQL Server data and Exchange directory information can be accessed from the Outlook 2000 client
Using Office Web Components Define the Office Web components Show how to create a Web page that uses the Microsoft Excel PivotTable® List control and Microsoft Access data access pages
Using ADO Provide an overview of OLE DB and describe its architecture Then, explain where ADO fits in this architecture Provide a high-level discussion of the main objects in the ADO object model Define an ADO recordset and describe how it is used
Retrieving Data from an ADO Data Source Describe the steps required to connect to a data source and return a
Recordset object Once students have learned how to return a recordset,
show some ways that they can work with it Show how to reference fields in
a recordset, explain how to use the Move methods to navigate through the records in a recordset, and how to use filtering to show only those records
that meet a specified criteria Finally, explain how to use the Command
object to execute a stored procedure
Updating Data in an ADO Data Source Describe two ways to update data in an ADO data source: by using the
Execute method of the Command and Connection objects, and by using a
recordset
Accessing Exchange Server Directory Information Describe the purpose of the Exchange Server directory and the different ways that developers can access the information that is stored there Discuss the objects in the Outlook object model that enable developers to access address book information Introduce CDO as another way to retrieve address book information Provide a definition of the Active Directory Service Interfaces (ADSI) and its provider-based model Explain how to view the directory schema and why this is important to developing ADSI applications Use the objects provided by ADSI to search the directory and update its contents
Trang 5Overview
Introduction to Data Access in Outlook 2000 Solutions
Using Office Web Components
Using ADO
Retrieving Data from an ADO Data Source
Updating Data in an ADO Data Source
Accessing Exchange Server Information
At the end of this module, you will be able to:
Describe the different ways that data can be accessed from the Microsoft® Outlook® 2000 client
Add a Microsoft Office Web component that connects to an external data source to a Web page
Define the relationship between Microsoft ActiveX® Data Objects (ADO) and OLE DB
Use ADO to connect to a data source, such as a Microsoft SQL Server™database, and retrieve data from that data source
Use ADO to add a new record to a data source
Define how Microsoft Active Directory™ Service Interfaces (ADSI), the directory access functions, and the Collaboration Data Objects (CDO) library can be used to access the Microsoft Exchange Server directory
In this module, you will learn
how to gain access to
various types of data from
your Outlook 2000 solutions
Trang 6Introduction to Data Access in Outlook 2000 Solutions
Using SQL Server Data from Outlook 2000
Microsoft Visual Basic or Visual Basic for Applications and ADO in Outlook 2000
Using the Exchange Server Directory from Outlook 2000
Using SQL Server Data from Outlook 2000
Two ways you can incorporate SQL Server data into your Outlook 2000 solution include:
Office Web Components and Data Access Pages Microsoft Office Web
components are Component Object Model (COM) controls that you can use
to publish interactive spreadsheets, charts, Microsoft PivotTable® lists, and databases for the Web Data access pages are interactive Web pages that maintain a live link to a host Access or SQL Server database With this live link, users can view, edit, and manipulate data within a browser window These components can be placed in a folder home page or an Outlook 2000 form to provide quick access to SQL Server data
Microsoft Visual Basic® or Visual Basic for Applications and ADO in Outlook 2000 Within Outlook 2000, you can use ADO from Microsoft
Visual Basic, Scripting Edition (VBScript), Visual Basic for Applications,
or a COM add-in You can use ADO to view, manipulate, add, or delete records in a SQL Server database
There are several ways that
you can use client-side data
access from the
Outlook 2000 client to SQL
Server and Exchange
Server directory data
sources
Trang 7Using the Exchange Server Directory from Outlook 2000
The Exchange Server directory contains information that you can use in your Outlook 2000 solutions For example, you can use the objects contained in the directory to set up mailboxes or to obtain information about mail recipients Several ways that you can access Exchange Server directory data from Outlook 2000 include:
Outlook Object Model The Outlook object model provides objects that you
can use to gain read-only access the Exchange Server address book
CDO The CDO Library is an interface to MAPI that provides an easy
method for gaining access to the directory information stored within an
Exchange Server Global Address List (GAL)
ADSI ADSI is a set of specifications of COM objects and interfaces that
you can use to manipulate Exchange Server directory services and other directory services You can use the ADSI objects to perform common administrative operations, such as adding new users or managing a print
queue
Trang 8Using Office Web Components
Introduction to Office Web Components
Publishing an Interactive Web Page from Excel
Using Data Access Pages
Using the Data Source Control
The Office Web components are COM controls that you can use to publish interactive spreadsheets, charts, PivotTable lists, and databases for the Web Office Web components provide a way to quickly add data access capabilities
to Outlook 2000 client applications You can base these components on an external data source, such as a SQL Server database, and then add them to Outlook 2000 forms or to folder home pages
Slide Objective
To outline this topic
Lead-in
Office Web components
provide a way to quickly add
data access capabilities to
client side applications
Trang 9Introduction to Office Web Components
Using Office Web Components in a Solution
Create a worksheet, PivotTable, or chart in Excel
Library
Capabilities of Office Web Components
Office Web components enable you to incorporate spreadsheets, PivotTable lists, charts, and data access pages into a solution in a number of different ways
Using Office Web Components in a Solution
You can use the Web components in your Outlook 2000 solution in the following ways:
Create a worksheet, PivotTable, or chart in Excel, and then save your work
as an interactive folder home page
Create a data access page in Access and save it as an interactive folder home page
Add a reference to the Microsoft Office Web Components Object Library to your custom application by using any development environment that supports COM; then use the components as you would any other COM object through automation
Use the Office Web components in Active Server Pages (ASP), and then generate static Hypertext Markup Language (HTML) or interactive Web pages for display on the Internet or intranet client
With Web components, users can interact with a Web page from within a browser, while using many of the features that are found in the full version of the application
Slide Objective
To describe the different
ways that Office Web
components can be used in
a solution and to list the
different components that
are available
Lead-in
Office Web components are
implemented as COM
controls, so they can be
used from Web pages or
any other development
environment that supports
COM
Trang 10Capabilities of Office Web Components
The following table lists and describes the capabilities of each component
Component Description
Spreadsheet Provides a recalculation engine, a full function library, and a
simple spreadsheet user interface A spreadsheet is created when a worksheet is saved with interactivity
PivotTable List Provides sorting, grouping, filtering, outlining, and pivoting
capabilities A PivotTable can connect to data from a spreadsheet range, a relational database, or a multidimensional database It can
be generated by Excel from a PivotTable object or designed with the Data Access Pages Designer in Access
Data Source The reporting engine behind data access pages and the PivotTable
component The data source component manages data access with the database servers by, for example, retrieving records and managing the sorting, filtering, and updating of records
Chart Graphically displays information from a spreadsheet, a
PivotTable, or the data source component A chart updates instantly in response to user interaction with the other components
Users must have Microsoft Internet Explorer version 4.01 (or later) and
an Office 2000 license to browse a Web page interactively by using Office Web components
Note
Trang 11Publishing an Interactive Web Page from Excel
C:\My Documents\Page.htm – Microsoft Internet Explorer provided by ITG
File Edit View Go Favorites Help
Links Address C:\My Documents\Page.htm
42 32 40 114
33 20 18 71
20 50 70
95 102 58 255 Sum of Quantity Sum of Quantity Sum of Quantity Sum of Quantity
My Computer
You create an interactive Web page from Excel by first creating the
spreadsheet, PivotTable, or chart and then clicking Save As Web Page on the
File menu
To publish an interactive Web page from Excel:
1 Activate the worksheet that contains the worksheet, PivotTable, or chart
2 On the File menu, click Save as Web Page
3 Click Publish
4 In the Choose list, select the type of data that you want to publish In the list
box, click the item that you want
5 Select the Add interactivity with check box, and then choose the type of
functionality (Spreadsheet, PivotTable, or Chart)
6 To add a title to the published section, click Change, enter the title that you want, and then click OK
7 Click the Browse button, and locate the drive, folder, Web folder, Web
server, or File Transfer Protocol (FTP) location where you want to publish your Web page
8 Click Publish
Slide Objective
To show a Web page that
uses Office Web
components
Lead-in
You create a Web page that
uses Office Web
components by first creating
the spreadsheet,
PivotTable, or chart in
Excel
Trang 12Using Data Access Pages
Category Entry Page – Microsoft Internet Explorer provided by ITG
File Edit View Go Favorites Help
Links Address C:\My Documents\Category Entry Page.htm
Description
Beverages Soft drinks, coffees, teas, beers, and ales
Categories 1 of 8
Done
Data access pages are interactive Web pages that maintain a live link to a host Access or SQL Server database With this live link, users can view, edit, and manipulate data within a browser window
You can create two types of data access pages—pages that support data entry and pages that are read-only You use the Page Wizard to create both types of data access pages
Slide Objective
To show a data access
page that is based on a SQL
Server database
Lead-in
To maintain a live link to an
Access or SQL Server
database, you must use
data access pages
Trang 13Creating a Data Entry Page
The Page Wizard makes creating a data entry page simple You specify the table or query that you want to use with the form, and the wizard creates a data input form for you
To create a data entry page by using the Page Wizard:
1 Open your database application
To open an existing SQL Server database in Access:
a On the File menu, click New
b On the Project tab, click Project (Existing Database), and then click
OK
c In the File New Database dialog box, enter a name for the database, and then click Create
d In the Data Link Properties dialog box, provide connection
information for the SQL Server database
e To make the data access page read-only, click the Advanced tab of the
Data Link Properties dialog box, specify access permissions, and then
click OK
The default value for access permissions is Share Deny None, which
means that all users can read and write to the database
2 On the Objects bar, click Pages
3 Double-click Create data access page by using wizard
4 In the Page Wizard dialog box, from the Tables/Queries list, select a table
Trang 14record-Using the Data Source Control
Function of the Data Source Control
and deliver records
Using the Data Source Control
connection
You can use the Data Source control directly, or indirectly through the use of the other Office Web components
Function of the Data Source Control
The Data Source control is the reporting engine behind data access pages, PivotTable List controls, and data-bound Chart controls The Data Source control has no visual representation at run time It is designed to manage the connection to the underlying data source and deliver records to be displayed by other controls on a Web page
The Data Source control relies on ADO for connections to relational data sources such as Access, SQL Server, or Oracle databases Although the Data Source control can provide data to the PivotTable List control, the Data Source control cannot be bound to multidimensional data sources; transformations of relational data to multidimensional data are managed by the PivotTable Service
Slide Objective
To describe the purpose of
the Data Source control and
how it is used
Lead-in
The Data Source control is
used to perform several
tasks for data access pages,
the PivotTable List control,
and the Chart control
Trang 15Using the Data Source Control
You can use the Data Source control to do the following:
Associate a DataSourceControl object with a database connection
Add a record (row) source (table, view, stored procedure, or SQL Server statement) to a Data Source control
Provide an ADO recordset to data-consuming objects on a Web page These objects include the Internet Explorer built-in controls that can be data bound, such as the TEXT or SELECT control, and all of the other Office Web Component controls
Build SQL Server commands to request data from relational data sources
Construct hierarchical (shaped) Recordset objects from one or more data
providers by using the services of the Microsoft Data Shaping Service for OLE DB service provider
Persist data in an Office Web component to a file or load data from a file to
an Office Web component
If you are creating a PivotTable list from a relational data source, the PivotTable Service is used to create a multidimensional data cube from the relational data bound to the Data Source control This data cube is then used by the PivotTable List control For multidimensional data sources, the PivotTable List control relies upon an OLE DB for online analytical processing (OLAP) provider The PivotTable Service is the OLE DB for OLAP provider for Microsoft SQL Server OLAP Services
Note
Trang 16Using ADO
Overview of OLE DB Technology
Using the ADO Object Model
ADO technology is supported by a variety of Microsoft development platforms, including Visual Basic, Visual Basic for Applications, Microsoft Visual Basic, Scripting Edition (VBScript), Microsoft Visual C++®, Microsoft Visual FoxPro®, and Microsoft Visual InterDev®
ADO provides the programmatic interface between OLE DB data and your applications The ADO object model defines a group of objects that allow you
to connect your application to a data source, retrieve and manipulate data from the data source, and disconnect from the data source when you finish using the data
One of the major benefits of ADO is that it requires fewer calls to achieve the same result as earlier data access technologies, such as Remote Data Objects (RDO) Recall that in the Outlook 2000 VBScript environment, all object variables must be declared by using the Variant data type Consequently, these objects use late binding When objects are late bound, a simpler object model results in better performance because there are fewer calls to properties and methods ADO offers the benefits of simplicity without sacrificing
Trang 17Overview of OLE DB Technology
Data Providers
Database
Visual Basic Application Visual C++ Application
Other Applications ASP Page
Non Relational Data ODBC
OLE DB Provider
ADO provides the interface between Office 2000 applications and OLE DB data OLE DB is Microsoft’s strategic, system-level programming interface to access data throughout an organization Whereas Open Database Connectivity (ODBC) is designed to allow access to relational data, OLE DB is an open standard that is designed to allow access to all kinds of data
Conceptually, OLE DB has three types of components: data providers, data consumers, and service components ADO handles the application-level programming
Data Providers
Data providers are applications (such as SQL Server or Exchange Server), or operating system components (such as a file system) that include data that other applications may need to access These data providers supply the OLE DB interfaces that data consumers or service components can access directly ODBC also has an OLE DB provider that makes ODBC data available to OLE
DB data consumers The examples in this module use SQL Server as the data provider
Data Consumers
Data consumers are applications that use the data exposed by data providers ADO technology provides the programmatic interface for using OLE DB data Any application that uses ADO is an OLE DB data consumer The examples in this module are written by using VBScript, and assume that an Outlook 2000 form is the data consumer
Slide Objective
To show the relationship
between data consumers,
service components, and
data providers in the OLE
Trang 18or interpretation of SQL Server queries
Advantages of ADO
ADO is a set of high-level Automation interfaces over OLE DB data Although OLE DB is a powerful interface for manipulating data, most application developers do not need the low level of control that OLE DB provides over the data-access process Most collaborative solutions do not need to explicitly manage memory resources, manually aggregate components, and other low-level operations Additionally, developers often use high-level languages that
do not support function pointers and other C++ call mechanisms ADO provides the following advantages to programmers:
Ease of use The data-access task analogous to “Hello World” requires only
three lines of code
Programming language neutral ADO can be used from languages such as
Microsoft Visual Basic, Java, C++, VBScript, and Microsoft JScript®
Provider neutral ADO can access data from any OLE DB source In
addition, ADO adapts gracefully to support less functional OLE DB providers
No loss of OLE DB functionality ADO allows C++ programmers access to
the underlying OLE DB interfaces
Extensible ADO can dynamically expose properties specific to a data
provider by means of collections of provider properties In addition, it provides type extensibility by allowing access to COM objects exposed as column values (for example, rowset and stream)
Trang 19Using the ADO Object Model
Error (Optional) Field
Parameter (Optional) Recordset
Property (Optional)
Connection
Properties Collection (Optional)
Execute Method Execute Method
Active Connection Property
ADO objects provide you with fast and easy access to all types of data The
ADO object model contains seven objects: Connection, Command,
Recordset, Parameter, Field, Property, and Error It also contains four types
of collections: Fields, Properties, Parameters, and Errors
With ADO, you do not have to navigate through the object hierarchy to create
the objects; you can create all objects independently, except for the Error,
Field, and Property objects Access to the Errors collection and Error object
occurs through the Connection object after a provider error occurs When data exists in the Recordset object, you can access the Fields collection and Field object through the Recordset object The metadata information of the
Recordset object can be viewed through the Fields collection and the Field
object
Main Components of the ADO Object Model
The three main components of the ADO object model are the Connection object, the Command object, and the Recordset object
Connection Object
The Connection object is the highest-level object in the ADO object model It
is used to make a connection between the application and a data source, such as
an Access database or a SQL Server database
Command Object
A Command object is a definition of a specific command that you intend to
execute against a data source, for example, a SQL Server statement or a stored SQL Server procedure
Slide Objective
To show the ADO object
model
Lead-in
The simple ADO object
hierarchy makes it relatively
straightforward to connect to
a data source and use its
data
Trang 20Recordset Object
By using the Recordset object, you can access the records that a database table
or a SQL Server query return With the Recordset object, you can navigate the
returned records, modify existing records, add new records, or delete specific records
Setting a Reference to ADO
Before you can use the ADO object model in your Visual Basic for Applications code, you need to set a reference to the ADO Object Library
To set the reference to the ADO Object Library:
1 On the Tools menu in the Visual Basic Editor, click References
2 Select Microsoft ActiveX Data Objects 2.1 Library, and then click OK
This step is not necessary if you are using the ADO object model from within an Outlook 2000 form
Trang 21Retrieving Data from an ADO Data Source
Establishing a Connection
Creating a Recordset Object
Referencing Fields and Data
Navigating Records
Filtering Records
There are two basic steps to retrieving data from a data source with ADO: establish a connection to the data source, and then create a new recordset Once you have created a recordset, you can use its properties and methods to work with its data
Slide Objective
To outline this topic
Lead-in
To retrieve data from a data
source you must complete
two tasks: establish a
connection to the data
source and then create a
new recordset
Trang 22Establishing a Connection
Declaring a Connection Object
Setting Connection Properties
Opening the Connection
Dim cnNorthwind Set cnNorthwind = _
Item.Application.CreateObject("ADODB.Connection")
Dim cnNorthwind Set cnNorthwind = _
Item.Application.CreateObject("ADODB.Connection")
With cnNorthwind
.Provider = "SQLOLEDB"
.ConnectionString = "User ID=sa;Password=;" & _
"Data Source=MyServer;" & _
"Initial Catalog=Northwind"
End With
With cnNorthwind
.Provider = "SQLOLEDB"
.ConnectionString = "User ID=sa;Password=;" & _
"Data Source=MyServer;" & _
Connection object You specify characteristics of the data source, such as the
data type and location, by setting properties of the Connection object, and then
opening the connection
After you have established a connection to a data source, you can use that connection to create one or more recordsets
Declaring a Connection Object
To establish a connection to the data source, first declare a Connection object
in your application and then create an instance of it
The following code declares and creates an instance of a new Connection
object
Dim cnNorthwind Set cnNorthwind = _ Item.Application.CreateObject("ADODB.Connection")
that data source is the first
step in using ADO
Trang 23Setting Connection Properties
The Connection object contains information about connections to OLE DB service providers Use the Connection object properties to specify the type of
data source and other information that the OLE DB provider needs to connect
to the data source
Property Description Provider Indicates the name of the OLE DB provider for the connection
The OLE DB provider for SQL Server is specified as
SQLOLEDB
The OLE DB provider for ADSI is specified as ADsDSOObject.
The OLE DB provider for Microsoft Jet 4.0 (for Access
databases) is specified as Microsoft.Jet.OLEDB.4.0
ConnectionString Contains the information that is used to establish a connection to
a data source
SQL Server requires this property but Access does not This information is typically passed to Access when the connection is
opened, rather than by using the ConnectionString property
The following example sets the Provider and ConnectionString properties for
the cnNorthwind connection This code establishes a connection to the SQL Server Northwind database
With cnNorthwind .Provider = "SQLOLEDB"
ConnectionString = "User ID=sa;Password=;" & _ "Data Source=MyServer;" & _
"Initial Catalog=Northwind"
End With
For a complete listing of ADO Connection object properties, search for
“Connection object (ADO)” in Visual Basic Help
Opening the Connection
After you have specified an OLE DB data provider and have passed the
connection information (if required), use the Open method to establish a
connection to the data source
The following example opens the connection to the Northwind SQL Server database
cnNorthwind.Open
Note
Trang 24Creating a Recordset Object
Creating a Recordset Object
Closing the Recordset and Connection Objects
Dim rsCustomersSet rsCustomers = _Item.Application.CreateObject("ADODB.Recordset")With rsCustomers
.CursorType = adOpenStatic.Open "Customers", cnNorthwindEnd With
Dim rsCustomersSet rsCustomers = _Item.Application.CreateObject("ADODB.Recordset")With rsCustomers
.CursorType = adOpenStatic.Open "Customers", cnNorthwindEnd With
' Close objects and clean uprsCustomers.Close
cnNorthwind.CloseSet rsCustomers = NothingSet cnNorthwind = Nothing
' Close objects and clean uprsCustomers.Close
cnNorthwind.CloseSet rsCustomers = NothingSet cnNorthwind = Nothing
When you use the Recordset object, your application can access data returned from a table or a SQL Server query By using the Recordset object, you can
navigate the records that have been returned, edit their values, add records, or delete records
Creating a Recordset Object
To build a Recordset object that is based on an active connection to a database, first declare and create an instance of a new Recordset object, and then open the Recordset object
Declaring a Recordset Object
The following code declares and creates an instance of a new Recordset object
Dim rsCustomers Set rsCustomers = _ Item.Application.CreateObject("ADODB.Recordset")
In this code example, the Set statement creates a new instance of the recordset
If rsCustomers contains a reference to a different Recordset object, then that
reference will be released when the new one is assigned
Setting Recordset Object Properties
The values that you specify for the CursorType and LockType properties
determine the functionality of the recordset that you created For example, the
constant, adOpenStatic, requests a static type cursor when opening the
recordset A static cursor is a static copy of a set of records that you can use to find data or generate reports Additions, changes, or deletions made by other users after you opened a static copy of the records will not be visible
Slide Objective
To show an example of
creating a Recordset
object, and closing the
Recordset object and
connection objects
Lead-in
Once a connection to a data
source has been
established, you can create
one or more Recordset
objects that are based on
that single connection
Trang 25The following table lists and describes the properties of the Recordset object
that are commonly used to create a recordset
Property Description CursorType Sets the cursor type The default is adOpenForwardOnly For more
information on CursorType, search for “CursorType property
(ADO)” in Visual Basic Help
LockType Sets the type of record locking The default constant is
adLockReadOnly For more information on LockType, search for
“LockType property (ADO)” in Visual Basic Help
For a complete listing of Recordset object properties, search for
“Recordset object (ADO)” in Visual Basic Help
Opening a Recordset Object
You create a new recordset from an existing Connection object Use the Open method of the Recordset object to open the recordset The Open method opens
a recordset that is based on a particular table or on the result of a SQL Server statement
The following example creates a Recordset object, sets the cursor type to static,
and then opens the Customers table in the Northwind database
Dim rsCustomers Set rsCustomers = _ Item.Application.CreateObject("ADODB.Recordset")
With rsCustomers .CursorType = adOpenStatic .Open "Customers", cnNorthwind End With
In the code for the Open method, Customers is the name of the table and cnNorthwind is the name of the Connection object variable
Note
Trang 26Closing the Recordset and Connection Objects
After you open a recordset and finish using it, you should close the recordset and release resources held by the object variables If you do not close the recordset, your application will waste memory and your recordset may keep a lock on a table, preventing other updates to the data To close a recordset and
remove the variable from memory, use the Close method of the Recordset object, and then set the object variable equal to Nothing
You should also use the Close method to close the Connection object when
you are done After closing the connection, you should also remove the object
variable from memory by setting it equal to Nothing
The following code closes and removes a Recordset object and a Connection
object from memory:
'Close objects and clean up rsCustomers.Close
cnNorthwind.Close Set rsCustomers = Nothing Set cnNorthwind = Nothing
Trang 27Referencing Fields and Data
Referencing Fields in a Recordset
Populating Controls in an Outlook 2000 Form
rsCustomers.Fields("ContactName")
rsCustomers.Fields("ContactName")
' Populate.oftSet FormPages = _Item.Application.ActiveInspector.ModifiedFormPagesSet MembershipPage = FormPages("Get Data")
Set txtCompany = _MembershipPage.Controls("txtCompanyName")Set txtContact = _
MembershipPage.Controls("txtContactName")txtCompany.Text = rsCustomers.Fields("CompanyName")txtContact.Text = rsCustomers.Fields("ContactName")
' Populate.oftSet FormPages = _Item.Application.ActiveInspector.ModifiedFormPagesSet MembershipPage = FormPages("Get Data")
Set txtCompany = _MembershipPage.Controls("txtCompanyName")Set txtContact = _
MembershipPage.Controls("txtContactName")txtCompany.Text = rsCustomers.Fields("CompanyName")txtContact.Text = rsCustomers.Fields("ContactName")
When working with records in a recordset, you can programmatically refer to the fields of each record
Referencing Fields in a Recordset
The Fields collection of a Recordset object represents the Field objects in a
row of data or in a record To use a field in a record, refer to the field by name
The following code accesses the ContactName field of the rsCustomers
recordset:
rsCustomers.Fields("ContactName")
Populating Controls in an Outlook 2000 Form
After you have created a recordset, you can manually reference the fields of the recordset to present their values to the user For example, if the Outlook 2000 form that you are using has two text boxes—one text box to display the customer’s company name and a second text box to display the customer’s name—you can populate the text boxes manually This process must be repeated every time that the user navigates to a new record
The following code populates the text boxes on a form
' Populate.oft Set FormPages = _ Item.Application.ActiveInspector.ModifiedFormPages Set MembershipPage = FormPages("Get Data")
Set txtCompany = MembershipPage.Controls("txtCompanyName") Set txtContact = MembershipPage.Controls("txtContactName") txtCompany.Text = rsCustomers.Fields("CompanyName")
txtContact.Text = rsCustomers.Fields("ContactName")
Slide Objective
To show the different ways
that you can reference data
in a field
Lead-in
There are two ways to
access data in a field for the
current record in a
recordset
Trang 28Navigating Records
Move Methods
MovePrevious
Using Move Methods to Create Navigation Buttons
BOF and EOF Properties
Sub cmdPrevious_Click()
' MoveMethods.oft rsCustomers.MovePrevious 'Check to see if tried to move prior to the _ first record
If rsCustomers.BOF Then
rsCustomers.MoveFirst End If
End Sub
Sub cmdPrevious_Click()
' MoveMethods.oft rsCustomers.MovePrevious 'Check to see if tried to move prior to the _ first record
If rsCustomers.BOF Then
rsCustomers.MoveFirst End If
End Sub
You can only access one record within a recordset at a given time The record currently being accessed is called the current record When you open a new recordset, the first record listed in the recordset becomes the current record by
default Navigation through a Recordset object is based on a record pointer A
record pointer indicates which record in the recordset is the current record Because only one record can be current, you navigate record-by-record by using
a variety of methods and properties to locate a specific record within the recordset Imagine that an invisible pointer highlights the current record as you move through the recordset
Move Methods
Five move methods enable you to navigate through the records in a Recordset object: Move, MoveFirst, MoveLast, MoveNext, and MovePrevious The
move methods allow a user to move to the first, last, next, or previous record in
a Recordset object and make that record the current record The following table
lists and describes when to use each of these move methods
Method Use to Move Move the position of the current record by the number of rows you
specify
MoveFirst Make the first record the current record
MoveLast Make the last record the current record
Slide Objective
To list the properties and
methods of the Recordset
object that support
navigation
Lead-in
Each Recordset object has
a current record You can
access different records in
the recordset by changing
the position of the current
record
Trang 29(continued)
Method Use to MoveNext Make the next record the current record
If the last record is the current record and you call the MoveNext
method, the current record is set to the position after the last record inthe recordset, and end-of-file (EOF) is set to True An attempt to move forward beyond this point generates an error
MovePrevious Make the previous record the current record
If the first record is the current record and you call the
MovePrevious method, the current record is set to the position
before the first record in the recordset, and beginning-of-file (BOF) is set to True An attempt to move backward beyond this point
generates an error
To use move methods that move backward in the Recordset object, such
as the MovePrevious, MoveFirst, or Move method (when specifying the
NumRecords parameter as a negative number), the Recordset object must be
opened by using a value of the CursorType property that supports moving backward If you do not specify the CursorType property when opening a
Recordset object, the default value (adForwardOnly) will be used, which only
supports moving forward
Using Move Methods to Create Navigation Buttons
You can use the move methods to create and control navigation buttons in your application By using the navigation buttons, a user can navigate to specific records The following example responds to the Click event of the MoveFirst
button to navigate to the first record in the rsCustomers recordset
Sub cmdMoveFirst_Click() ' MoveMethods.oft rsCustomers.MoveFirst End Sub
The following example uses the Click event to create a MoveLast button that
navigates to the last record in the rsCustomers recordset
Sub cmdMoveLast_Click() ' MoveMethods.oft rsCustomers.MoveLast End Sub
Note
Trang 30BOF and EOF Properties
You use the BOF and EOF properties to determine whether a Recordset object
contains records or to determine when you have moved beyond the records contained in a recordset while moving from record to record
When you open a Recordset object, the current record is positioned at the first record (if one exists) and the BOF and EOF properties are set to False The
BOF property returns True if the current record position is before the first
record The EOF property returns True if the current record position is after the last record If the recordset contains no records, the BOF and EOF property settings are both True The following example uses the BOF property in the
Click event to create a MovePrevious button that navigates to the previous
record in the rsCustomers recordset
Sub cmdPrevious_Click() ' MoveMethods.oft rsCustomers.MovePrevious 'Check to see if tried to move prior to the first record
If rsCustomers.BOF Then rsCustomers.MoveFirst End If
If rsCustomers.EOF Then rsCustomers.MoveLast End If
End Sub
In this example, if the user tries to move beyond the last record, the user is set back to the last record and the error is avoided
Trang 31You can reduce the number of records that are returned to the Recordset object
by creating expressions that filter records from the selected tables or views The
Filter property on a Recordset object indicates a filter for data in a recordset Using the Filter Property
By using the Filter property of a Recordset object, you can limit the records
that are presented The original records are still available in memory, but only those records that meet the filter’s requirements will be displayed as part of the recordset
The following example shows only those customers that are located in the United Kingdom
rsCustomers.Filter = "Country = 'UK'"
Disabling a Filter
To return a recordset to its original contents, set the Filter property to the
adFilterNone constant The following example disables a filter, making all
original records available
rsCustomers.Filter = adFilterNone Setting the Filter property to "" (zero-length string) has the same effect as setting the property to adFilterNone
Slide Objective
To show how to filter
records
Lead-in
Filters enable you to
temporarily limit the records
available in a recordset,
without requiring your
application to run a new
query against the data
source