Download One… ADO Data Control

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Microsoft SQL Server wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Database wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Concurrency control wikipedia , lookup

Relational model wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Clusterpoint wikipedia , lookup

Functional Database Model wikipedia , lookup

Database model wikipedia , lookup

Transcript
Database Access using ADO – I
(ADO Data Control &
Data Bound Control)
Vivek Gupta
IT & Systems Group
Indian Institute of Management
Lucknow
1
One…
ADO Data Control
2
ADO Data Control
• The ADO (ActiveX Data Object) data control is the
primary interface between a Visual Basic application
and a database.
– It can be used without writing any code at all! Or,
– It can be a central part of a complex database
management system.
– The ADO data control does not appear in the standard
Visual Basic toolbox - it must be added.
» Select Project from the main menu, then click
Components. The Components window will appear.
Select Microsoft ADO Data Control, then click OK. The
control will be added to your toolbox.
• The data control (or tool) can access databases created by
other programs besides Visual Basic (or MS Access).
– Some other formats supported include dBase, FoxPro,
and Paradox.
3
A form that uses an ADO data control
Description
• An ADO data control defines the recordset for a
form and provides functions for navigating,
displaying, adding, and updating records.
• Bound controls automatically display the values
in the fields in the current record of the recordset
that’s defined by a data control.
4
Updating records with a data control
• The user can change the data in any one of the
bound controls.
• Then, when the user clicks on one of the
navigation buttons in the data control to move to
another record, the current record is automatically
updated.
• If the user closes the form before moving to
another record, though, the changes are lost.
Deleting records with a data control
• Some functions, like deleting records, aren’t built
into the data control.
• To provide for these functions, you use Visual
Basic code.
5
Two…
Data Bound Control
Would be revisiting ADO Data Control soon…
6
Data Bound Controls
• Controls that are tied to database fields and
are generally not available for free-form
input.
– they automatically display database fields.
(Data aware controls is a synonym.)
• Data-Bound controls on the form:
– Set the bound control’s DataSource property
to point to the data control
– set the bound control’s DataField property to
the database field it is to display
7
Data Bound Controls (contd’)
• The DataChanged property is set to True whenever a bound
control’s contents are changed by the user.
– Before ending a program, be sure to check the DataChanged
property of every bound control to see if the user made
changes.
– As data is displayed in the bound controls, the
DataChanged property is set to False.
» If the user or any other operation changes the value in the
bound control, the DataChanged property is set to True.
» Simply moving to another record doesn't affect the
DataChanged property.
– When the data control starts to move to a different record,
the Validate event occurs.
» If DataChanged is True for any bound control, the data
control automatically invokes the Edit and Update methods to
post the changes to the database.
– If you don't wish to save changes from a bound control to
the database, you can set the DataChanged property to
False in the Validate event
8
Data BoundControls
• Special controls with properties established by
database fields.
– A data bound control is needed for each field (column)
in the Recordset (database table) we need to view.
– Most of the standard Visual Basic tools can be used
as data bound controls
» Label: used to provide display-only access to a
specified text data field.Caption property is data bound.
» Text Box: used to provide read/write access to a
specified text data field. Text property is data bound.
» Check Box: Used to provide read/write access to a
Boolean field. Value property is data bound.
» Picture Box & Image Box: Used to display a graphical
image from a bitmap, icon, gif, jpeg, or metafile file.
Provides read/write access to a image/binary data field.
Picture property is data bound.
9
Data BoundControls (contd’)
•
•
•
Three ‘custom’ data bound controls,
– data bound versions of the standard list box (DataList), the
standard combo box (DataCombo), and the standard grid control
(DataGrid).
Properties: To establish the connection of the data bound control to a
database, we use a few properties:
– DataChanged: Indicates whether a value displayed in a bound
control has changed.
– DataField: Specifies the name of a field in the table pointed to by
the respective data control.
– DataSource: Specifies which data control the control is bound to
(indirectly specifying the database table).
If the data in any data bound control is changed and the user
moves to another record in the database, the database will
automatically be updated with the new data (assuming it is not
ReadOnly).
– Be aware of this - it is an extremely powerful feature of the
data control, but also a potential source of problems.
10
Data BoundControls (contd’)
• Steps in placing the controls on a form:
– Draw the bound control on the same form as the data
control to which it will be bound.
– Set the DataSource property. Click on the drop-down arrow
to list the data controls on your form. Choose one.
– Set the DataField property. Click on the drop-down arrow to
list the fields associated with the selected data control
records. Make your choice.
– Set all other properties, as needed.
11
An Example…
12
Back to…
ADO Data Control
13
ADO Data Control
• The data control can perform the following tasks:
–
–
–
–
Connect to a database.
Open a specified database table.
Create a virtual table based on a database query.
Pass database fields to other Visual Basic tools, for
display or editing. Such tools are bound to the
database, or data bound controls.
– Add new records, delete records, or update records.
– Trap any errors that may occur while accessing data.
– Close the database.
• As a rule, you need one data control for every
database table, or virtual table, you need access to.
– One row of the table is accessible to each data control
at any one time.
» This is referred to as the current record
14
ADO Data Control
•
When an ADO data control is placed on a form, it
appears with the assigned caption and four arrow
buttons:
–
•
Move to first/previous/last/next record
The arrows are used to navigate through the table
records (rows).
–
–
The buttons can be used to move to the beginning of
the table, the end of the table, or from record to
record.
In most applications, the data control never appears
on the form – its Visible property is almost always
False.
15
ADO Data Control Properties
• The ADO data control is connected to a database simply
be setting a few properties. Important properties of this
data control are:
–
–
–
–
–
–
–
–
–
Align: Determines where data control is displayed.
Caption: Phrase displayed on the data control.
CommandType: Establishes source of Recordset (table or query).
ConnectionString: Contains the information used to establish a
connection to a database.
EditMode: Read-only at run-time. Indicates current state of editing for the
current record.
LockType: Indicates the type of locks placed on records during editing
(default setting makes databases read-only).
Recordset: A set of records defined by a data control’s ConnectionString
and RecordSource properties. Run-time only.
RecordSource: Determines the table (or virtual table) the data control is
attached to
Visible: Establishes whether the data control appears on the form at runtime
16
More ADO data control properties
Pro pe rty
UserName
Password
EOFAction
BOFAction
De s c riptio n
If a user name isn’t included in the
ConnectionString property, it must be
specified for this property.
If a password isn’t included in the
ConnectionString property, it must be
specified for this property.
Determines what happens when the user
tries to move past the last record in the
recordset.
Determines what happens when the user
tries to move past the first record in the
recordset.
17
ConnectionString Property
• After placing a data control on a form, we
set the ConnectionString property.
• The ADO data control can connect to a
variety of database types.
• There are three ways to connect to a
database:
–
–
–
using a data link,
using an ODBC data source, or
using a connection string.
18
Two dialog boxes for building a connection string
19
ConnectionString Property
•
•
Visual Basic can build the connection string for us.
The steps to create our example connection string
are:
–
–
–
–
–
–
–
Start a new Visual Basic project and place an ADO Data Control on
the form.
Go to the Properties Window, click on the Connection String. Click
on the ellipsis that appears. The Property Pages window appears.
Choose Use Connection String and click the Build button. The
Data Link Properties window appears.
Choose the Provider tab and select Microsoft Jet 4.0 OLE DB
Provider (an Access database).
Click the Next button to go to the Connection tab.
Click the ellipsis and use the Select Access Database dialog box to
choose the BIBLIO.MDB file in your working directory. Click
Open.
Click Test Connection. Then, click OK (assuming it passed). Click
OK in the Property Pages window. The connection string is built
and assigned to the ConnectionString property of the data control.
20
ADO Data Control Events
• Events that are triggered at various times during database
access, where we write code to perform specific needed
tasks.
– WillMove: Triggers before record pointer is moved from one row to
another.
– MoveComplete: Event triggered after record pointer has been moved from
one row to another.
– EndofRecordset: Triggers when the record pointer is moved past the last
record in the recordset.
– WillChangeRecordset: Triggers before a change is made to the
recordset. Used to trap unwanted changes.
– RecordsetChangeComplete: Triggers after a change is made to
recordset.
– WillChangeRecord: Triggers before updates for the current row are sent
to the data source.
– RecordChangeComplete: Triggers after updates for the current row are
sent to the data source.
– WillChangeField: Triggers before the current field in the recordset is
updated.
– FieldChangeComplete: Triggers after the current field in the recordset
has been updated
21
DAO vs. ADO ?
• The primary difference between the two data
controls is in the properties used to connect to a
database.
– The DAO control connects to the database using the
DatabaseName property while the ADO control uses
the ConnectionString.
– To construct a Recordset, the DAO control uses the
RecordSource property. The ADO control requires
setting two properties: RecordSource and
CommandType.
– The ADO data control offers more event procedures
than the DAO control to allow more complete control
over database management
22
ADO Recordset Object
•
•
An important concept.
When we set the RecordSource property (either
select a table from the database or form a virtual
table via a query), the data control (using the Jet
engine) retrieves the needed records and places
them in the Recordset object for our use.
–
This object has its own properties and methods for our
use.
23
The Recordset Object
• Is at the heart of every VB application that
manipulates databases.
• It is a programmable object where cursors are stored
– Through this object, we can manipulate the rows of a
cursor, view their fields, and update the underlying
tables.
• An important aspect of Recordsets is that we can
choose their location – whether they’ll reside on the
server, or whether they’ll be downloaded to the
client.
• Another important property is that it can be
disconnected from its source and we can still process
it on the client, and on reconnecting to the server, we
can update the underlying tables.
24
ADO Recordset Properties
• Can only be accessed at run-time.
– To refer to a Recordset property, use a 'double-dot' notation.
e.g., if you have a data control named datExample, to refer
to a property named PropertyName, the notation is :
» datExample.Recordset.PropertyName
• Important data control Recordset properties are:
– AbsolutePosition: Long integer that either gets or sets the
position of the current record.
– BOF: Returns True when the current record is positioned before
any data.
– Bookmark: Sets or returns a bookmark to the current record.
Used as a place marker in database management tasks.
– EditMode: Indicates the state of editing for the current record.
– EOF: Returns True when the current record is positioned past any
data.
– RecordCount: The total number of records in the Recordset.
25
ADO Recordset Methods
• Important Recordset methods are:
– AddNew: Adds a new record to the Recordset. All fields are set to null
and this record becomes the current record.
– CancelUpdate: Used to cancel any pending updates (either while
editing or using the AddNew method)
– Close: Closes a Recordset.
– Delete: The current record is deleted from the Recordset.
– Move: Moves the current record pointer a specified number of records
forward or backward.
– MoveFirst: Moves the current record pointer to the first record in the
Recordset.
– MoveLast : Moves the current record pointer to the last record in the
Recordset.
– MoveNext : Moves the current record pointer to the next record in the
Recordset.
– MovePrevious: Moves the current record pointer to the previous
record in the Recordset.
– Requery: Updates the data in a Recordset object by re-executing the
query on which the object is based.
– Update: Saves the current contents of all data bound controls
26
Example: Recordset Navigation
• cmdPrevious_Click event:
Private Sub cmdPrevious_Click()
datTitles.Recordset.MovePrevious
If datTitles.Recordset.BOF Then
datTitles.Recordset.MoveFirst
End If
End Sub
• cmdNext_Click event:
Private Sub cmdNext_Click()
datTitles.Recordset.MoveNext
If datTitles.Recordset.EOF Then
datTitles.Recordset.MoveLast
End If
End Sub
27
Data Environment
28
ADO Data Environment
• The Data Environment acts like multiple data controls we
can access from anywhere in our application.
– We can connect to multiple databases and form multiple
views of the data in those databases.
– Data bound controls can bind to any data view in the Data
Environment
• The Data Environment is a shareable and reusable
connection file that can be used in any VB project.
– It is added to our project just like a form
» (it has a single property of interest - Name).
• The Data Environment provides a greatly simplified
programming environment used to connect to data
sources.
– It provides 'drag-and-drop' functionality for building
interfaces and developing database reports
29
ADO Data Environment
• The Data Environment
has two primary objects:
– the Connection object
» specifies the database
similar to the
ConnectionString
property of the ADO
data control, and
– the Command object
» specifies the
Recordset like the
RecordSource
property of the ADO
control.
30
The Connection Object
• Establishes a connection to a database, which is then
used to execute commands against the database or
retrieve a Recordset
– Its most important property is the ConnectionString
property, which specifies the database we want to
connect to.
– To establish a connection through a Connection object,
call its Open method
» Use Close method to close this connection when not
needed
– To find out whether a connection is open, use its State
property
31
Connection Object
• It specifies the information needed to connect to a
particular database.
• The Connection object has several properties:
– Attributes: Needed connection string properties
passed to the Connection object.
– CommandTimeout: Time in seconds the server will
wait for a command to return a reply.
– ConnectionSource: String that describes the path to
the data source connection.
– ConnectionTimeout: Time in seconds the server will
wait for a connection to open on the destination server
32
Command Object
• The Command object specifies a database table
(either a native table or a virtual table formed using
a database query).
• Some Command object properties are:
– CommandText: Specifies table to display or gives
valid database query statement.
– CommandType: Specifies whether object is
connected to database native table or virtual table
formed using a query.
– ConnectionName: Name of associated Connection
object.
– LockType: Controls how data in table may or may not
be changed. Set to Read Only by default. Must be
changed if you need to edit data.
33
Example: Use of ADO Data Environment
• Here, we will form a Connection object to
the books database (BIBLIO.MDB) database
and a Command object for the Titles table.
– This should illustrate the differences between
using the Data Environment and the ADO
data control
34
Data bound controls with Data Environment
• To establish the connection of a data bound
control to a database using the Data
Environment, we use three properties:
– DataField: Specifies the name of a field in the
table established by the Command object.
– DataMember: Specifies the Command object
establishing the database table.
– DataSource: Specifies which Data
Environment the control is bound to.
» NB: there is one more property needed when
compared to using the ADO data control DataMember is not used with the data control
35
Data bound controls with Data Environment
• The relationships between a data bound
control (DataSource, DataMember and
DataField properties) and the Data
Environment are:
36
Data bound controls with Data Environment
• To use bound controls with the Data Environment,
steps are:
– Draw the bound control on the form.
– Set the DataSource property. Click on the drop-down
arrow to list the Data Environments in your project.
Choose one.
– Set the DataMember property. Click on the dropdown arrow to list the Command objects in the
selected Data Environment. Choose one.
– Set the DataField property. Click on the drop-down
arrow to list the fields associated with the selected
DataMember. Make your choice.
– Set all other properties, as needed
37
‘Drag and Drop’ Data Bound Controls
• One of the powerful features of the Data
Environment
• Recordsets in the Data Environment
– the Data Environment returns a Recordset that has
properties and methods identical to those of the ADO
data control.
» A Recordset is returned for each Command object in the
environment.
» Each possible recordsets in one Data Environment is
assigned a unique name by the environment, based on
the Command object name.
• Make sure you give each Command object in a Data
Environment a unique name.
38
Example: Use of Drag & Drop
• Here, we will build the same interface with
the ADO data control using the drag & drop
capabilities off the Data Environment.
39
Recordsets in the Data Environment
• For a Command object named comExample,
the Recordset is assigned the name
rscomExample (note the addition of the two
letter prefix, rs).
– To read or set the property of this Recordset
in a Data Environment named denExample,
we use the double-dot notation of:
» denExample.rscomExample.PropertyName
– Likewise to reference a method (such as one
of the Move methods) for this Recordset, we
use the notation:
» denExample.rscomExample.MethodName
40
Example: Record Navigation with D.EN.
• Continuing with previous eg., we will add two
command buttons
• cmdPrevious_Click event:
Private Sub cmdPrevious_Click()
denBooks.rscomTitles.MovePrevious
If denBooks.rscomTitles.BOF Then
denBooks.rscomTitles.MoveFirst
End If
End Sub
41
The Data Environment Designer window
42
How to use the Designer window
• To open the Designer window, you can select More
ActiveX Designers from the Project menu and then select
Data Environment.
• When the Designer window is opened for the first time for
a project, one DataEnvironment object and one
Connection object are shown.
• To change the name of the DataEnvironment object, select
it in either the Designer or Project Explorer window, then
change the name in the Properties window.
• To change the way the objects are arranged in the Data
Environment Designer window, click on the Arrange By
Connections or the Arrange By Objects toolbar buttons.
• To remove a DataEnvironment object from a project,
select the object in the Project Explorer window and chose
the Remove command from either the Project menu or the
shortcut menu.
43
The Provider and Connection tabs of the Data Link
Properties dialog box
44
How to edit or create a Connection object
• To edit a Connection object, select that object in the
Designer window and click on the Properties button in
the Designer toolbar.
• To create a new Connection object, click on the Add
Connection button in the Designer toolbar.
• When the Data Link Properties dialog box is displayed,
you must complete the Properties and Connection tabs
as you did in chapters 6 and 7.
• When you add a Connection object to the Designer
window, it’s also added to the Data View window
that's presented in chapter 11. However, you have to
use the Designer window, not the Data View window,
to edit the properties of the Connection object or to see
its Command objects.
45
The General tab of the Properties
dialog box for a Command object
46
How to create a Command object
• To create a new Command object, click on the Add
Command button on the Designer toolbar. This displays the
General tab of the Properties dialog box for the Command
object.
• From the General tab, enter a name for the command and
choose one of the Connection objects that has been created
for the DataEnvironment object.
• Then, if you click on the Database Object button, you can
select Stored Procedure, Table, or View from the first dropdown list and the stored procedure, table, or view that you
want to use as the data source from the Object Name list.
• Or, if you click on the SQL Statement button, you can enter
an SQL statement as the data source.
• To build an SQL statement for a command using a graphical
interface, you can click on the SQL Builder button.
47
A bound form created from a Command object
48
How to build a form from a Command object
• To create a bound form from a Command object, drag the
object and drop in onto the form.
• To add individual fields to a form, expand the Command object
in the Designer window so it shows all the fields defined by the
object. Then, drag-and-drop one field name at a time onto the
form.
• If you look at the Data properties for a bound control that has
been added to the form in this way, you will see that the
DataSource property is set to the designer name (deAP), the
DataMember property is set to the command name (Vendors),
and the DataField property is set to the field name.
• After you add the controls to the form, you can move or edit
them in the usual ways.
• To complete a form, you need to add navigation controls that
let the user move from one record to another.
49
The Options and Field Properties dialog boxes
Description
• You can use the Options dialog box to change the general
defaults for the way controls are added to a form.
• You can use the Field Properties dialog box to change the
mapping default or caption for a single field.
50
A completion list for a DataEnvironment object
Statements that refer to properties and methods
deAP.rsVendors.RecordCount
deAP.rsVendorInvoices.EOF
deAP.rsVendors.MoveFirst
deAP.rsVendorInvoices.Find
51
The Query Designer window for a query that
retrieves data from two tables
52
How to use the Query Designer
• When you're creating or editing a Command object, you can use the Query
Designer to generate the SQL query that you need. To do that, click the
SQL Builder button on the General tab of the Properties dialog box for a
Command object.
• When the Query Designer starts, the Data View window that's described in
chapter 11 is also opened. Then, to add tables to the query, you drag them
from the Data View window and drop them in the diagram pane of the
Query Designer.
• To include a field in the query and add it to the grid pane, check its box in
the diagram pane. To include all the fields in a table, check the All
Columns box. To include a calculated field, enter an expression in the
Column column.
• To sort the records based on one or more fields, choose Ascending or
Descending from the drop-down list in the Sort Type column.
53
How to use the Query Designer (continued)
• To select the records to be included in the results, enter criteria in the
Criteria and Or columns of the grid pane. If you want to use a field to
select records but you don’t want to include it in the results, remove the
check mark from the Output column for the field.
• To execute the SQL statement that's shown in the SQL pane, select the
Run command from the Query menu or the shortcut menu. If the query
returns a recordset, the data is displayed in the results pane. Otherwise,
you’ll see a message indicating how many records were affected by the
query.
• To save the SQL statement in the Command object, close the Query
Designer window and click Yes in the resulting dialog box.
• To resize a pane, drag its top or bottom boundary. To hide or show a
pane, use the Hide Pane command in the shortcut menu or the Show
Panes submenu of the View menu.
54
Return to ADO…
55
Three…
ADO Object Model
56
The ActiveX Data Object (ADO) model
Connection
Recordset
Fields
Field
Command
Parameters
Errors
Parameter
Error
57
ADO concepts
• The Connection object represents a connection to
a data source.
• A Recordset object represents a set of records
returned from a query.
• You can use the Fields collection of a Recordset
object to refer to specific fields in the recordset.
• A collection is simply a set of objects of the same
type.
• A Command object contains the definition of a
command, such as a SQL statement, the name of
a table, or the name of a stored procedure.
• You can use the Parameters collection of a
Command object to create parameter queries or to
specify arguments for a stored procedure.
58
ADO concepts (continued)
• The Errors collection contains one or more Error
objects that contain information about the most
recent errors that occurred in response to an ADO
operation.
• You can use these objects to get more
information than the Visual Basic Err object
provides.
• The ADO model lets you access a data source
using an object-oriented interface.
• That means you can use the same syntax to
access data objects that you use to access objects
like forms and controls.
• The ADO model also provides a variety of
properties, methods, and events for working with
the ActiveX data objects.
59
How does ADO work ?
• ADO is a component for accessing databases
– It exposes a few very flexible objects, which expose
their own properties, methods, and recognize events
• The structure of the ADO object model reflects the
operations we perform on a database,
– We can even guess these objects and their names once
we understand what it takes to access and update a
database.
• First step to using ADO is to connect to a database
– This connection object is our gateway to the database
60
Common ADO properties
Prope rty
ConnectionString
Provider
DefaultDatabase
CursorLocation
BOF
EOF
CursorType
LockType
RecordCount
Obje c t
Connection
Connection
Connection
Connection
Recordset
Recordset
Recordset
Recordset
Recordset
61
Common ADO methods
Me tho d
Open
AddNew
Update
Delete
MoveFirst
MoveLast
MovePrevious
MoveNext
Requery
Close
Obje c t
Connection
Recordset
Recordset
Recordset
Recordset
Recordset
Recordset
Connection
Recordset
62
Typical declarations for ADO variables
Dim cnAP As Connection
Dim rsVendors As Recordset
Typical assignment statements for ADO
variables
Set cnAP = New Connection
Set rsVendors = New Recordset
Set rsVendors = Nothing
Typical statements for working with
ADO variables
rsVendors.Open "Vendors",cnAP,adOpenKeyset, _
adLockOptimistic,adCmdTable
txtName = rsVendors!VendorName
If rsVendors.EOF Then rsVendors.MoveLast
rsVendors.Close
63
Description
• Use the Dim statement (Private or Public) to declare an object
variable for an ADO object
– After above declaration, we use the Set statement to create
an instance of the object and assign a reference to the
object to the variable.
» To do this, we use the New keyword and the name of the ADO
object
– After creating an instance of an object, we can refer to its
properties, methods, and events in the code.
• To disassociate a variable from the object it refers to, assign a
value of Nothing to the value. Then, the system resources
associate with the object are released.
• To refer to a field in a recordset, code the recordset name, the
bang operator (!), and the field name
– as in, rsVendors!VendorName
64
A procedure that deletes a record from the data
source associated with a data control
Private Sub cmdDelete_Click()
If MsgBox("Do you want to delete this record?", _
vbYesNo + vbDefaultButton2 + vbQuestion) _
= vbYes Then
adoVendors.Recordset.Delete
adoVendors.Recordset.MoveNext
If adoVendors.Recordset.EOF Then
adoVendors.Recordset.Requery
adoVendors.Recordset.MoveLast
End If
End If
End Sub
65
Understanding
Cursors & Recordsets
66
Cursors & Recordsets
• There is a direct relationship between SQL Server cursors and
VB Recordsets.
– Every time we issue a SELECT statement, SQL Server
retrieves the qualifying rows and returns them to the caller,
which is a stored procedure or a Visual Basic application.
» This set of rows is called a cursor
• When the cursor is passed to the VB application, its stored in a
Recordset object.
• The cursor contains the info. retrieved from the DB, the “raw”
information.
• A Recordset is an ADO object that stores these rows. It contains
the functionality we need to access these rows in the form of
properties and methods.
– A recordset is simply an object that references a cursor.
– It exposes a number of methods and properties we can use
to navigate the cursor (not the Recordset) and edit the rows
of the underlying cursor.
67
Cursors & Recordsets
• A typical application sets up a connection to a
database and executes commands through this
connection, but it spends most of its time processing
the rows returned by the DBMS
• After establishing a connection to the database and
preparing the command object, we can execute the
command and retrieve the cursor. However, we
must prepare an object where the cursor will be
stored.
– This object is a Recordset variable, that must be
declared as: Dim RS as ADODB.Recordset
– Then execute the command with theExecute method
and assign the cursor returned to the RS variable:
» Set RS = Cmd.Execute
68
Types of Cursors
• Different applications have different requirements,
which get reflected by the cursor-related properties
as well as by the LockType property
• Cursors are categorized according to their type
(CursorType property) and where they reside
(CursorLocation property)
– The type of cursor determines how ‘fresh’ the cursor
is, i.e., whether the application can see changes made
to the cursor by other users or not.
» If the cursor resides on the client,then its type is static
» Other types apply to cursors that reside on server.
69
CursorLocation options
Option
adUseClient
adUseServer
Des cription
The cursor and its associated result set
reside on the client.
The cursor and its associated result set
reside on the server.
Note
• If we use client-side cursors (adUseClient), Visual Basic
automatically sets the cursor type to adOpenStatic without
notifying us, no matter what we set the CursorType to.
70
CursorType options
Optio n
adOpenDynamic
adOpenKeyset
De s c riptio n
Opens a dynamic cursor, which includes
changes, additions, and deletions made to
the database by other users.
Uses keys to identify individual records.
Cannot be used to create sorted result sets
from SQL Server data.
Opens a keyset cursor, which includes
changes made to the database by other
users.
Additions made by other users aren’t
visible, but records deleted by other users
are no longer accessible.
Uses keys to identify individual records.
71
CursorType options (continued)
Option
adOpenStatic
adOpenForwardOnly
Des cription
Opens a static cursor, which doesn’t
include changes, additions, and deletions
made to the database by other users.
This is the only type of cursor that can be
created on the client with ADO.
Opens a forward-only cursor.
This cursor is like a static cursor, but you
can only scroll forward through the
records.
This type of cursor isn’t available when
you define a recordset using a data control.
72
Three…
ADO Saga Continues…
73
LockType options
Optio n
adLockReadOnly
adLockPessimistic
De s c riptio n
Data can be viewed, but not modified.
When used with SQL Server data, this
causes a shared lock to be placed on the
records so other users can access and
change the data at the same time.
Causes the records to be locked
immediately so other users can’t change
them.
When used with SQL Server data, this
causes an update lock to be placed on the
records when they’re retrieved. The
update lock is upgraded to an exclusive
lock when the records are actually
updated.
74
LockType options (continued)
adLockOptimistic
adLockBatchOptimistic
Causes the records to be locked when
they’re updated.
When used with SQL Server data, this
causes a shared lock to be placed on the
records when they’re retrieved. Then,
when the Update method is issued, the
shared lock is upgraded to an update lock.
And when the records are actually
updated, the update lock is upgraded to an
exclusive lock.
Used for updating records in batches
instead of one at a time.
75
An Unbound form using code to maintain vendor records
Description
• The navigation buttons are an array of command buttons.
• When a record is first displayed, the Update button is disabled. As soon
as the user makes a change to the data in the form, however, the Update
button is enabled and the Add, Delete, and navigation buttons are
disabled.
• To save the changes, the user must click on the Update button or press
the Enter key to activate the Update button.
76
Description (continued)
• To cancel the changes, the user can press the Esc key.
• When the user clicks on the Add button, the controls are
cleared, the Update button is enabled, and the Add,
Delete, and navigation buttons are disabled.
• After the data for the new record is entered into the
form, the user can save the record by clicking on the
Update button or pressing the Enter key.
• To cancel the addition, the user can press the Esc key.
• If the user clicks on the Update button to add a new
record or modify an existing record and a required field
hasn’t been entered, a message box is displayed
identifying the field.
• When the user presses the Delete key, a dialog box is
displayed to confirm the delete operation. If the user
confirms the operation, the record is deleted and the
next record in the recordset is displayed.
77
Functions that are provided through code
Func tio n
Open connection
Open recordset
Recordset
navigation
Move values
from fields to
controls
Me tho d o r
s tateme nt
Open method
Open method
MoveFirst,
MovePrevious,
MoveNext,
MoveLast
Assignment
statements
Whe n e xe c ute d
When the form is loaded
When the form is loaded
When the user clicks on a
navigation button or
when other events require
this movement
When the recordset is
opened, when the user
clicks on a navigation
button, when a record is
deleted, and when
changes to a record are
canceled
78
More functions that are provided through code
Fu n c tio n
Clear control
values
Add a new
record to the
recordset
M ove values
from controls to
current record,
and update the
recordset
Close a
connection or
recordset
Me th o d o r
s ta te m e n t
Assignm ent
statements
AddNew
m ethod
Wh e n e x e c u te d
Assignm ent
statements,
Update m ethod
W hen the user indicates
that recordset should be
updated with the data for
a new record or the
changes to an old record
W hen the connection or
recordset is no longer
needed
Close method
W hen the user wants to
add a record
W hen the user wants to
add a record
79
Open method syntax for a Connection object
connection.Open [ConnectionString][, UserID][, Password]
ConnectionString arguments for SQL Server
Arg um e nt
Provider
Server/Data
Source
Database/
Initial Catalog
UID/UserID
PWD/Password
De s c riptio n
The name of the OLE DB provider
(SQLOLEDB)
The name of the server where the database
resides
The name of the database
The user name to use when connecting to
the data source
The password to use when connecting to the
data source
80
Statements that open a connection to a SQL
Server database
Dim cnAP As Connection
Set cnAP = New Connection
cnAP.CursorLocation = adUseClient
cnAP.Open "Provider=SQLOLEDB;Server=mmaserver;" _
& "Database=AccountsPayable", "ed", "abc4xyz"
81
Open method syntax for a Recordset object
recordset.Open [Source][, ActiveConnection][, CursorType]
[, LockType][, Options]
Arg ume nt
Source
ActiveConnection
CursorType
LockType
Options
De s c riptio n
A SQL statement, the name of a table, or
the name of a stored procedure.
A valid Connection object or string.
The type of cursor to be used for the
recordset
The type of locking to be used for the
recordset
The type of information specified in the
Source argument
82
Statements that open a recordset with a SELECT
statement and a Connection object
Dim rsVendors As Recordset, strSQL As String
Set rsVendors = New Recordset
strSQL = "SELECT * FROM Vendors ORDER BY VendorName"
rsVendors.Open strSQL, cnAP, adOpenKeyset, _
adLockOptimistic, adCmdText
Statements that open the same recordset using a
connection string and no Connection object
Dim strConnection As String
strConnection = "Provider=SQLOLEDB;Server=mmaserver;" _
& "UID=ed;PWD=abc4xyz;Database=AccountsPayable"
rsVendors.Open strSQL, strConnection, adOpenKeyset, _
adLockOptimistic, adCmdText
83
The properties for two controls in an array
Description
• To create a control array, you add two or more controls of
the same type to the form.
• Then, you change the names of the controls so they’re all the
same and Visual Basic sets the Index property of each
control so it’s unique.
84
How to use a control array
• To refer to a control in an array, you use the control
name followed by its index number in parentheses,
starting with zero for the first control in the array as in
this example:
cmdNavigate(0)
• The controls in a control array are treated as a group. So
we code a single event procedure for the entire array
• When an event occurs on a control in an array, Visual
Basic passes an argument to the event procedure that
contains the index of the control that the event occurred
on. Then, you can use that index to determine the
processing that’s done.
85
Code for working with the control array
Private Sub cmdNavigate_Click(Index As Integer)
Select Case Index
Case 0
rsVendors.MoveFirst
Case 1
rsVendors.MovePrevious
If rsVendors.BOF Then rsVendors.MoveFirst
Case 2
rsVendors.MoveNext
If rsVendors.EOF Then rsVendors.MoveLast
Case 3
rsVendors.MoveLast
End Select
End Sub
86
Code for the unbound Vendors form
Option Explicit
1
Dim mcnAP As Connection
Dim mrsVendors As Recordset
Dim mbAddNew As Boolean
Const msDialogTitle = "Chapter 6 - Vendors (Unbound)"
Private Sub Form_Load()
2
Set mcnAP = New Connection
Set mrsVendors = New Recordset
mcnAP.Open "Provider=SQLOLEDB;Server=mmaserver;" _
& "Database=AccountsPayable", "ed",
"abc4xyz"
mrsVendors.Open _
"SELECT * FROM Vendors ORDER BY VendorName", _
mcnAP, adOpenKeyset, adLockOptimistic, adCmdText
LoadControls
SetCommandButtons True
SetNavigationButtons True
End Sub
87
Private Sub LoadControls()
With mrsVendors
txtName = !VendorName
txtAddress1 = !VendorAddress1 & ""
txtAddress2 = !VendorAddress2 & ""
txtCity = !VendorCity
txtState = !VendorState
txtZipCode = !VendorZipCode
txtContact = !VendorContact & ""
txtPhone = !VendorPhone & ""
End With
End Sub
3
Private Sub SetCommandButtons(bVal As Boolean)
cmdAdd.Enabled = bVal
cmdUpdate.Enabled = Not bVal
cmdUpdate.Default = Not bVal
cmdDelete.Enabled = bVal
End Sub
4
88
Private Sub SetNavigationButtons(bVal As Boolean)
Dim i As Integer
For i = 0 To 3
cmdNavigate(i).Enabled = bVal
Next
End Sub
5
89
Private Sub cmdNavigate_Click(Index As Integer)
With mrsVendors
Select Case Index
Case 0
.MoveFirst
Case 1
.MovePrevious
If .BOF Then .MoveFirst
Case 2
.MoveNext
If .EOF Then .MoveLast
Case 3
.MoveLast
End Select
End With
LoadControls
SetCommandButtons True
SetNavigationButtons True
txtName.SetFocus
End Sub
6
90
Private Sub cmdAdd_Click()
mbAddNew = True
ClearControls
SetCommandButtons False
txtName.SetFocus
End Sub
7
Private Sub ClearControls()
txtName = ""
txtAddress1 = ""
txtAddress2 = ""
txtCity = ""
txtState = ""
txtZipCode = ""
txtContact = ""
txtPhone = ""
End Sub
8
91
Private Sub cmdUpdate_Click()
On Error GoTo ErrorHandler
If ValidData Then
If mbAddNew Then mrsVendors.AddNew
LoadRecord
mrsVendors.Update
mbAddNew = False
SetCommandButtons True
SetNavigationButtons True
txtName.SetFocus
End If
Exit Sub
ErrorHandler:
DisplayErrorMsg
If mrsVendors.EditMode = adEditAdd Then
mrsVendors.CancelUpdate
End Sub
9
92
Private Function ValidData() As Boolean
Dim strMessage As String
If txtName = "" Then
txtName.SetFocus
strMessage = "You must enter a vendor name."
ElseIf txtCity = "" Then
txtCity.SetFocus
strMessage = "You must enter a city."
ElseIf txtState = "" Then
txtState.SetFocus
strMessage = "You must enter a state code."
ElseIf txtZipCode = "" Then
txtZipCode.SetFocus
strMessage = "You must enter a zip code."
Else
ValidData = True
End If
If Not ValidData Then
MsgBox strMessage, vbOKOnly, msDialogTitle
End If
End Function
10
93
Private Sub LoadRecord()
With mrsVendors
!VendorName = txtName
!VendorAddress1 = txtAddress1
!VendorAddress2 = txtAddress2
!VendorCity = txtCity
!VendorState = txtState
!VendorZipCode = txtZipCode
!VendorContact = txtContact
!VendorPhone = txtPhone
End With
End Sub
11
94
Private Sub cmdDelete_Click()
12
On Error GoTo ErrorHandler
If MsgBox("Do you want to delete this record?", _
vbYesNo + vbDefaultButton2 + vbQuestion, _
msDialogTitle) _
= vbYes Then
With mrsVendors
.Delete
.MoveNext
If .EOF Then
.Requery
.MoveLast
End If
LoadControls
End With
End If
SetCommandButtons True
SetNavigationButtons True
txtName.SetFocus
Exit Sub
ErrorHandler:
DisplayErrorMsg
End Sub
95
Private Sub txtName_Change()
SetNavigationButtons False
SetCommandButtons False
End Sub
13
Private Sub txtAddress1_Change()
SetNavigationButtons False
SetCommandButtons False
End Sub
.
.
.
Private Sub txtPhone_Change()
SetNavigationButtons False
SetCommandButtons False
End Sub
96
Private Sub Form_KeyDown(KeyCode As Integer, _
Shift As Integer)
If KeyCode = vbKeyEscape Then
LoadControls
SetCommandButtons True
SetNavigationButtons True
End If
End Sub
14
Private Sub cmdExit_Click()
mrsVendors.Close
mcnAP.Close
Set mrsVendors = Nothing
Set mcnAP = Nothing
Unload frmVendors
End
End Sub
15
Private Sub DisplayErrorMsg()
MsgBox "Error Code: " & Err.Number & vbCrLf & _
"Description: " & Err.Description, _
vbOKOnly + vbCritical, msDialogTitle
End Sub
16
97
When bound forms are best
• When the forms are relatively simple
• When the built-in functions are acceptable to the users
• When you need to build an application quickly without full
functionality
When unbound forms are best
• When the forms are relatively complex
• When the user interface needs to work in a way that can't be
accomplished with bound forms
• When you can't get the bound forms to do what you want them to
do without serious debugging problems (see chapter 7)
Notes
• You can combine the use of bound and unbound forms.
• Unbound forms are commonly used for critical business
applications.
98