7 DB Access Using ADO&DataEnv
Transcript of 7 DB Access Using ADO&DataEnv
-
8/8/2019 7 DB Access Using ADO&DataEnv
1/49
1
Database Access using ADO I
(ADO Data Control &
Data Bound Control)
Vivek Gupta
IT & Systems Group
Indian Institute of Management
Lucknow
2
OneADO Data Control
-
8/8/2019 7 DB Access Using ADO&DataEnv
2/49
3
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 standardVisual Basic toolbox - it must be added.
Select Project from the main menu, then clickComponents. The Components window will appear.
Select Microsoft ADO Data Control, then click OK. Thecontrol will be added to your toolbox.
The data control (or tool) can access databases created byother programs besides Visual Basic (or MS Access).
Some other formats supported include dBase, FoxPro,and Paradox.
4
A form that uses an ADO data control
Description
AnADOdata control defines the recordsetfor aform and provides functions for navigating,
displaying, adding, and updating records.
Bound controls automatically display the valuesin the fields in the current record of the recordset
thats defined by a data control.
-
8/8/2019 7 DB Access Using ADO&DataEnv
3/49
5
Updating records with a data control
The user can change the data in any one of thebound controls.
Then, when the user clicks on one of thenavigation buttons in the data control to move to
another record, the current record is automatically
updated.
If the user closes the form before moving toanother record, though, the changes are lost.
Deleting records with a data control
Some functions, like deleting records, arent builtinto the data control.
To provide for these functions, you use VisualBasic code.
6
Two
Data Bound Control
Would be revisiting ADO Data Control soon
-
8/8/2019 7 DB Access Using ADO&DataEnv
4/49
7
Data Bound Controls
Controls that are tied to database fields and
are generally not available for free-forminput.
they automatically display database fields.(Data aware controls is a synonym.)
Data-Bound controls on the form:
Set the bound controls DataSource propertyto point to the data control
set the bound controls DataFieldproperty tothe database field it is to display
8
Data Bound Controls (contd) The DataChanged property is set to True whenever a bound
controls 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 madechanges.
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 datacontrol automatically invokes the Edit and Update methods topost the changes to the database.
If you don't wish to save changes from a bound control tothe database, you can set the DataChanged property toFalse in the Validate event
-
8/8/2019 7 DB Access Using ADO&DataEnv
5/49
9
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 usedas data bound controls
Label : used to provide display-only access to aspecified text data field.Caption property is data bound.
Text Box: used to provide read/write access to aspecified 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.
10
Data BoundControls (contd) Three custom data bound controls,
data bound versions of the standard list box (DataList), thestandard combo box (DataCombo), and the standard grid control(DataGrid).
Properties: To establish the connection of the data bound control to adatabase, we use a few properties:
DataChanged: Indicates whether a value displayed in a boundcontrol has changed.
DataField: Specifies the name of a field in the table pointed to bythe 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 usermoves to another record in the database, the database willautomatically 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.
-
8/8/2019 7 DB Access Using ADO&DataEnv
6/49
11
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 controlrecords. Make your choice.
Set all other properties, as needed.
12
An Example
-
8/8/2019 7 DB Access Using ADO&DataEnv
7/49
13
Back toADO Data Control
14
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, fordisplay or editing. Such tools are bound to thedatabase, 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 everydatabase table, or virtual table, you need access to.
One row of the table is accessible to each data controlat any one time.
This is referred to as the current record
-
8/8/2019 7 DB Access Using ADO&DataEnv
8/49
15
ADO Data Control
When an ADO data control is placed on a form, itappears with the assigned caption and four arrowbuttons:
Move to first/previous/last/next record
The arrows are used to navigate through the tablerecords (rows).
The buttons can be used to move to the beginning ofthe table, the end of the table, or from record torecord.
In most applications, the data control never appearson the form its Visible property is almost alwaysFalse.
16
ADO Data Control Properties The ADO data control is connected to a database simply
be setting a few properties. Important properties of thisdata 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 thecurrent 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 controls 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 run-
time
-
8/8/2019 7 DB Access Using ADO&DataEnv
9/49
17
More ADO data control properties
Pro pe rty De s criptio n
UserName If a user name isnt included in the
ConnectionString property, it must bespecified for this property.
Password If a password isnt included in the
ConnectionString property, it must be
specified for this property.
EOFAction Determines what happens when the user
tries to move past the last record in the
recordset.
BOFAction Determines what happens when the usertries to move past the first record in the
recordset.
18
ConnectionString Property
After placing a data control on a form, weset the ConnectionString property.
The ADO data control can connect to avariety of database types.
There are three ways to connect to adatabase: using a data link,
using an ODBC data source, or
using a connection string.
-
8/8/2019 7 DB Access Using ADO&DataEnv
10/49
19
Two dialog boxes for building a connection string
20
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. ClickOpen.
Click Test Connection. Then, click OK (assuming it passed). ClickOK in the Property Pages window. The connection string is builtand assigned to the ConnectionString property of the data control.
-
8/8/2019 7 DB Access Using ADO&DataEnv
11/49
21
ADO Data Control Events Events that are triggered at various times during database
access, where we write code to perform specific neededtasks.
WillMove: Triggers before record pointer is moved from one row toanother.
MoveComplete: Event triggered after record pointer has been moved fromone row to another.
EndofRecordset: Triggers when the record pointer is moved past the lastrecord in the recordset.
WillChangeRecordset: Triggers before a change is made to therecordset. Used to trap unwanted changes.
RecordsetChangeComplete: Triggers after a change is made torecordset.
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 isupdated.
FieldChangeComplete: Triggers after the current field in the recordset
has been updated
22
DAO vs. ADO ?
The primary difference between the two data
controls is in the properties used to connect to adatabase.
The DAO control connects to the database using the
DatabaseName property while the ADO control usesthe ConnectionString.
To construct a Recordset, the DAO control uses theRecordSource property. The ADO control requires
setting two properties: RecordSource andCommandType.
The ADO data control offers more event procedures
than the DAO control to allow more complete controlover database management
-
8/8/2019 7 DB Access Using ADO&DataEnv
12/49
23
ADO Recordset Object
An important concept.
When we set the RecordSource property (eitherselect a table from the database or form a virtualtable via a query), the data control (using the Jetengine) 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.
24
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 underlyingtables.
An important aspect of Recordsets is that we canchoose their location whether theyll reside on theserver, or whether theyll be downloaded to theclient.
Another important property is that it can be
disconnected from its source and we can still processit on the client, and on reconnecting to the server, wecan update the underlying tables.
-
8/8/2019 7 DB Access Using ADO&DataEnv
13/49
25
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 referto 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 beforeany 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 anydata.
RecordCount: The total number of records in the Recordset.
26
ADO Recordset Methods Important Recordset methods are:
AddNew: Adds a new record to the Recordset. All fields are set to nulland this record becomes the current record.
CancelUpdate: Used to cancel any pending updates (either whileediting 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 recordsforward or backward.
MoveFirst: Moves the current record pointer to the first record in theRecordset.
MoveLast : Moves the current record pointer to the last record in theRecordset.
MoveNext : Moves the current record pointer to the next record in theRecordset.
MovePrevious: Moves the current record pointer to the previousrecord in the Recordset.
Requery: Updates the data in a Recordset object by re-executing thequery on which the object is based.
Update: Saves the current contents of all data bound controls
-
8/8/2019 7 DB Access Using ADO&DataEnv
14/49
27
Example: Recordset Navigation
cmdPrevious_Click event:Private Sub cmdPrevious_Click()
datTitles.Recordset.MovePreviousIf 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 ThendatTitles.Recordset.MoveLast
End If
End Sub
28
Data Environment
-
8/8/2019 7 DB Access Using ADO&DataEnv
15/49
29
ADO Data Environment
The Data Environment acts like multiple data controls wecan access from anywhere in our application.
We can connect to multiple databases and form multipleviews of the data in those databases.
Data bound controls can bind to any data view in the DataEnvironment
The Data Environment is a shareable and reusableconnection 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 simplifiedprogramming environment used to connect to datasources. It provides 'drag-and-drop' functionality for building
interfaces and developing database reports
30
ADO Data Environment
The Data Environmenthas two primary objects:
the Connection object
specifies the database
similar to theConnectionStringproperty of the ADO
data control, and
the Command object
specifies theRecordset like theRecordSourceproperty of the ADO
control.
-
8/8/2019 7 DB Access Using ADO&DataEnv
16/49
31
The Connection Object
Establishes a connection to a database, which is thenused to execute commands against the database orretrieve a Recordset Its most important property is the ConnectionString
property, which specifies the database we want toconnect to.
To establish a connection through a Connection object,call its Open method
Use Close method to close this connection when notneeded
To find out whether a connection is open, use its Stateproperty
32
Connection Object
It specifies the information needed to connect to aparticular 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 willwait for a connection to open on the destination server
-
8/8/2019 7 DB Access Using ADO&DataEnv
17/49
33
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 givesvalid database query statement.
CommandType: Specifies whether object isconnected to database native table or virtual tableformed 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 bechanged if you need to edit data.
34
Example: Use of ADO Data Environment
Here, we will form a Connection object tothe books database (BIBLIO.MDB) databaseand a Command object for the Titles table.
This should illustrate the differences betweenusing the Data Environment and the ADOdata control
-
8/8/2019 7 DB Access Using ADO&DataEnv
18/49
35
Data bound controls with Data Environment
To establish the connection of a data boundcontrol to a database using the DataEnvironment, we use three properties:DataField: Specifies the name of a field in the
table established by the Command object.
DataMember: Specifies the Command objectestablishing 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
36
Data bound controls with Data Environment
The relationships between a data boundcontrol (DataSource, DataMember andDataField properties) and the Data
Environment are:
-
8/8/2019 7 DB Access Using ADO&DataEnv
19/49
37
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-downarrow to list the Data Environments in your project.Choose one.
Set the DataMember property. Click on the drop-
down arrow to list the Command objects in theselected Data Environment. Choose one.
Set the DataField property. Click on the drop-downarrow to list the fields associated with the selected
DataMember. Make your choice.
Set all other properties, as needed
38
Drag and Drop Data Bound Controls
One of the powerful features of the DataEnvironment
Recordsets in the Data Environment
the Data Environment returns a Recordset that hasproperties and methods identical to those of the ADO
data control.
A Recordset is returned for each Command object in theenvironment.
Each possible recordsets in one Data Environment is
assigned a unique name by the environment, based onthe Command object name.
Make sure you give each Command object in a DataEnvironment a unique name.
-
8/8/2019 7 DB Access Using ADO&DataEnv
20/49
39
Example: Use of Drag & Drop
Here, we will build the same interface withthe ADO data control using the drag & dropcapabilities off the Data Environment.
40
Recordsets in the Data Environment
For a Command object named comExample,the Recordset is assigned the namerscomExample (note the addition of the two
letter prefix, rs). To read or set the property of this Recordsetin a Data Environment named denExample,we use the double-dot notation of:
denExample.rscomExample.PropertyName
Likewise to reference a method (such as oneof the Move methods) for this Recordset, we
use the notation: denExample.rscomExample.MethodName
-
8/8/2019 7 DB Access Using ADO&DataEnv
21/49
41
Example: Record Navigation with D.EN.
Continuing with previous eg., we will add twocommand buttons
cmdPrevious_Click event:Private Sub cmdPrevious_Click()
denBooks.rscomTitles.MovePrevious
If denBooks.rscomTitles.BOF Then
denBooks.rscomTitles.MoveFirst
End If
End Sub
42
The Data Environment Designer window
-
8/8/2019 7 DB Access Using ADO&DataEnv
22/49
43
How to use the Designer window
To open the Designer window, you can select MoreActiveX Designers from the Project menu and then select
Data Environment.
When the Designer window is opened for the first time fora project, one DataEnvironment object and one
Connection object are shown.
To change the name of the DataEnvironment object, selectit 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 DataEnvironment 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.
44
The Provider and Connection tabs of the Data LinkProperties dialog box
-
8/8/2019 7 DB Access Using ADO&DataEnv
23/49
45
How to edit or create a Connection object
To edit a Connection object, select that object in theDesigner window and click on the Properties button in
the Designer toolbar.
To create a new Connection object, click on the AddConnection 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 Designerwindow, its 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.
46
The General tab of the Propertiesdialog box for a Command object
-
8/8/2019 7 DB Access Using ADO&DataEnv
24/49
47
How to create a Command object
To create a new Command object, click on the AddCommand 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 canselect Stored Procedure, Table, or View from the first drop-
down 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 enteran SQL statement as the data source.
To build an SQL statement for a command using a graphicalinterface, you can click on the SQL Builder button.
48
A bound form created from a Command object
-
8/8/2019 7 DB Access Using ADO&DataEnv
25/49
49
How to build a form from a Command object
To create a bound form from a Command object, drag theobject 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 theobject. 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 hasbeen 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 editthem in the usual ways.
To complete a form, you need to add navigation controls thatlet the user move from one record to another.
50
The Options and Field Properties dialog boxes
Description
You can use the Options dialog box to change the generaldefaults for the way controls are added to a form.
You can use the Field Properties dialog box to change themapping default or caption for a single field.
-
8/8/2019 7 DB Access Using ADO&DataEnv
26/49
51
A completion list for a DataEnvironment object
Statements that refer to properties and methodsdeAP.rsVendors.RecordCount
deAP.rsVendorInvoices.EOF
deAP.rsVendors.MoveFirst
deAP.rsVendorInvoices.Find
52
The Query Designer window for a query thatretrieves data from two tables
-
8/8/2019 7 DB Access Using ADO&DataEnv
27/49
53
How to use the Query Designer
When you're creating or editing a Command object, you can use the QueryDesigner 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 inchapter 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 inthe 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.
54
How to use the Query Designer (continued)
To select the records to be included in the results, enter criteria in theCriteria and Or columns of the grid pane. If you want to use a field to
select records but you dont 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 queryreturns a recordset, the data is displayed in the results pane. Otherwise,
youll see a message indicating how many records were affected by the
query.
To save the SQL statement in the Command object, close the QueryDesigner window and click Yes in the resulting dialog box.
To resize a pane, drag its top or bottom boundary. To hide or show apane, use the Hide Pane command in the shortcut menu or the Show
Panes submenu of the View menu.
-
8/8/2019 7 DB Access Using ADO&DataEnv
28/49
55
Return to ADO
56
ThreeADO Object Model
-
8/8/2019 7 DB Access Using ADO&DataEnv
29/49
57
The ActiveX Data Object (ADO) model
Connection
Recordset
Fields Field
Command
Parameters
Errors Error
Parameter
58
ADO concepts
The Connection object represents a connection toa data source.
A Recordset object represents a set of recordsreturned from a query.
You can use the Fields collection of a Recordsetobject to refer to specific fields in the recordset.
A collection is simply a set of objects of the sametype.
A Command object contains the definition of acommand, such as a SQL statement, the name of
a table, or the name of a stored procedure.
You can use the Parameters collection of aCommand object to create parameter queries or to
specify arguments for a stored procedure.
-
8/8/2019 7 DB Access Using ADO&DataEnv
30/49
59
ADO concepts (continued)
The Errors collection contains one or more Errorobjects that contain information about the most
recent errors that occurred in response to an ADO
operation.
You can use these objects to get moreinformation than the Visual Basic Err object
provides.
The ADO model lets you access a data sourceusing an object-oriented interface.
That means you can use the same syntax to
access data objects that you use to access objectslike forms and controls.
The ADO model also provides a variety ofproperties, methods, and events for working with
the ActiveX data objects.
60
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 theoperations we perform on a database,
We can even guess these objects and their names oncewe understand what it takes to access and update adatabase.
First step to using ADO is to connect to a database
This connection object is our gateway to the database
-
8/8/2019 7 DB Access Using ADO&DataEnv
31/49
61
Common ADO properties
Property Object
ConnectionString Connection
Provider ConnectionDefaultDatabase Connection
CursorLocation Connection
Recordset
BOF
EOF
Recordset
CursorType RecordsetLockType Recordset
RecordCount Recordset
62
Common ADO methods
Method Object
Open Connection
Recordset
AddNew Recordset
Update Recordset
Delete Recordset
MoveFirst
MoveLast
MovePrevious
MoveNext
Recordset
Requery Recordset
Close ConnectionRecordset
-
8/8/2019 7 DB Access Using ADO&DataEnv
32/49
63
Typical declarations for ADO variablesDim cnAP As Connection
Dim rsVendors As Recordset
Typical assignment statements for ADOvariablesSet cnAP = New Connection
Set rsVendors = New Recordset
Set rsVendors = Nothing
Typical statements for working withADO variablesrsVendors.Open "Vendors",cnAP,adOpenKeyset, _
adLockOptimistic,adCmdTabletxtName = rsVendors!VendorName
If rsVendors.EOF Then rsVendors.MoveLast
rsVendors.Close
64
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 instanceof the object and assign a reference to theobject to the variable.
To do this, we use the New keyword and the name of the ADOobject
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 avalue 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
-
8/8/2019 7 DB Access Using ADO&DataEnv
33/49
65
A procedure that deletes a record from the datasource 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
66
UnderstandingCursors & Recordsets
-
8/8/2019 7 DB Access Using ADO&DataEnv
34/49
67
Cursors & Recordsets
There is a direct relationship between SQL Server cursors andVB 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 aRecordset object.
The cursor contains the info. retrieved from the DB, the rawinformation.
A Recordset is an ADO object that stores these rows. It containsthe 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 rowsof the underlying cursor.
68
Cursors & Recordsets
A typical application sets up a connection to adatabase and executes commands through thisconnection, but it spends most of its time processingthe rows returned by the DBMS
After establishing a connection to the database andpreparing the command object, we can execute thecommand and retrieve the cursor. However, wemust prepare an object where the cursor will bestored. This object is a Recordset variable, that must be
declared as: Dim RS as ADODB.Recordset
Then execute the command with theExecute methodand assign the cursor returned to the RS variable:
Set RS = Cmd.Execute
-
8/8/2019 7 DB Access Using ADO&DataEnv
35/49
69
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 cursoris, i.e., whether the application can see changes madeto 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.
70
CursorLocation options
Option Des cription
adUseClient The cursor and its associated result set
reside on the client.
adUseServer 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.
-
8/8/2019 7 DB Access Using ADO&DataEnv
36/49
71
CursorType options
Option De s cription
adOpenDynamic 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.
adOpenKeyset Opens a keyset cursor, which includes
changes made to the database by other
users.
Additions made by other users arentvisible, but records deleted by other users
are no longer accessible.
Uses keys to identify individual records.
72
CursorType options (continued)
Option Description
adOpenStatic Opens a static cursor, which doesnt
include changes, additions, and deletionsmade to the database by other users.
This is the only type of cursor that can be
created on the client with ADO.
adOpenForwardOnly Opens a forward-only cursor.
This cursor is like a static cursor, but youcan only scroll forward through the
records.
This type of cursor isnt available when
you define a recordset using a data control.
-
8/8/2019 7 DB Access Using ADO&DataEnv
37/49
73
Three
ADO Saga Continues
74
LockType options
Option Des cription
adLockReadOnly 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.adLockPessimistic Causes the records to be locked
immediately so other users cant change
them.
When used with SQL Server data, this
causes an update lock to be placed on the
records when theyre retrieved. The
update lock is upgraded to an exclusive
lock when the records are actuallyupdated.
-
8/8/2019 7 DB Access Using ADO&DataEnv
38/49
75
LockType options (continued)
adLockOptimistic Causes the records to be locked when
theyre updated.
When used with SQL Server data, thiscauses a shared lock to be placed on the
records when theyre retrieved. Then,
when the Update method is issued, theshared lock is upgraded to an update lock.
And when the records are actually
updated, the update lock is upgraded to an
exclusive lock.
adLockBatchOptimistic Used for updating records in batchesinstead of one at a time.
76
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 soonas 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 pressthe Enter key to activate the Update button.
-
8/8/2019 7 DB Access Using ADO&DataEnv
39/49
77
Description (continued)
To cancel the changes, the user can press the Esc key.
When the user clicks on the Add button, the controls arecleared, the Update button is enabled, and the Add,
Delete, and navigation buttons are disabled.
After the data for the new record is entered into theform, 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 newrecord or modify an existing record and a required field
hasnt 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.
78
Functions that are provided through code
Function Metho d or
statement
When exe cuted
Open connection Open method When the form is loaded
Open recordset Open method When the form is loaded
Recordset
navigation
MoveFirst,
MovePrevious,
MoveNext,
MoveLast
When the user clicks on a
navigation button or
when other events require
this movement
Move values
from fields to
controls
Assignment
statements
When the recordset is
opened, when the user
clicks on a navigation
button, when a record is
deleted, and when
changes to a record arecanceled
-
8/8/2019 7 DB Access Using ADO&DataEnv
40/49
79
More functions that are provided through code
Fun c tio n Me th o d o r
s ta tem e nt
W h e n e x e c u te d
Clear control
values
Assignment
statements
When the user wants to
add a record
Add a new
record to the
recordset
AddNew
method
When the user wants to
add a record
Move values
from controls to
current record,
and update the
recordset
Assignment
statements,
Update method
When the user indicates
that recordset should be
updated with the data for
a new record or the
changes to an old recordClose a
connection or
recordset
Close m ethod W hen the connection or
recordset is no longer
needed
80
Open method syntax for a Connection objectconnection.Open [ConnectionString][, UserID][, Password]
ConnectionString arguments for SQL Server
Arg ume nt De s criptio n
Provider The name of the OLE DB provider
(SQLOLEDB)
Server/Data
Source
The name of the server where the database
resides
Database/
Initial Catalog
The name of the database
UID/UserID The user name to use when connecting to
the data source
PWD/Password The password to use when connecting to thedata source
-
8/8/2019 7 DB Access Using ADO&DataEnv
41/49
81
Statements that open a connection to a SQLServer databaseDim cnAP As Connection
Set cnAP = New Connection
cnAP.CursorLocation = adUseClient
cnAP.Open "Provider=SQLOLEDB;Server=mmaserver;" _
& "Database=AccountsPayable", "ed", "abc4xyz"
82
Open method syntax for a Recordset objectrecordset.Open [Source][, ActiveConnection][, CursorType]
[, LockType][, Options]
Argume nt Des c ription
Source A SQL statement, the name of a table, or
the name of a stored procedure.
ActiveConnection A valid Connection object or string.
CursorType The type of cursor to be used for the
recordset
LockType The type of locking to be used for the
recordset
Options The type of information specified in the
Source argument
-
8/8/2019 7 DB Access Using ADO&DataEnv
42/49
83
Statements that open a recordset with a SELECTstatement and a Connection objectDim rsVendors As Recordset, strSQL As String
Set rsVendors = New RecordsetstrSQL = "SELECT * FROM Vendors ORDER BY VendorName"
rsVendors.Open strSQL, cnAP, adOpenKeyset, _
adLockOptimistic, adCmdText
Statements that open the same recordset using aconnection string and no Connection objectDim strConnection As String
strConnection = "Provider=SQLOLEDB;Server=mmaserver;" _
& "UID=ed;PWD=abc4xyz;Database=AccountsPayable"
rsVendors.Open strSQL, strConnection, adOpenKeyset, _adLockOptimistic, adCmdText
84
The properties for two controls in an array
Description
To create a control array, you add two or more controls ofthe same type to the form.
Then, you change the names of the controls so theyre all the
same and Visual Basic sets the Index property of eachcontrol so its unique.
-
8/8/2019 7 DB Access Using ADO&DataEnv
43/49
85
How to use a control array
To refer to a control in an array, you use the controlname followed by its index number in parentheses,
starting with zero for the first control in the array as inthis example:
cmdNavigate(0)
The controls in a control array are treated as a group. Sowe code a single event procedure for the entire array
When an event occurs on a control in an array, VisualBasic 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 thats done.
86
Code for working with the control arrayPrivate 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
-
8/8/2019 7 DB Access Using ADO&DataEnv
44/49
87
Code for the unbound Vendors form
Option Explicit 1
Dim mcnAP As Connection
Dim mrsVendors As Recordset
Dim mbAddNew As BooleanConst 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, adCmdTextLoadControls
SetCommandButtons True
SetNavigationButtons True
End Sub
88
Private Sub LoadControls() 3
With mrsVendors
txtName = !VendorName
txtAddress1 = !VendorAddress1 & ""
txtAddress2 = !VendorAddress2 & ""
txtCity = !VendorCity
txtState = !VendorState
txtZipCode = !VendorZipCodetxtContact = !VendorContact & ""
txtPhone = !VendorPhone & ""
End With
End Sub
Private Sub SetCommandButtons(bVal As Boolean) 4
cmdAdd.Enabled = bVal
cmdUpdate.Enabled = Not bVal
cmdUpdate.Default = Not bVal
cmdDelete.Enabled = bVal
End Sub
-
8/8/2019 7 DB Access Using ADO&DataEnv
45/49
89
Private Sub SetNavigationButtons(bVal As Boolean) 5Dim i As Integer
For i = 0 To 3
cmdNavigate(i).Enabled = bVal
Next
End Sub
90
Private Sub cmdNavigate_Click(Index As Integer) 6
With mrsVendors
Select Case Index
Case 0
.MoveFirst
Case 1
.MovePrevious
If .BOF Then .MoveFirstCase 2
.MoveNext
If .EOF Then .MoveLast
Case 3
.MoveLast
End Select
End With
LoadControls
SetCommandButtons True
SetNavigationButtons True
txtName.SetFocusEnd Sub
-
8/8/2019 7 DB Access Using ADO&DataEnv
46/49
91
Private Sub cmdAdd_Click() 7
mbAddNew = True
ClearControls
SetCommandButtons FalsetxtName.SetFocus
End Sub
Private Sub ClearControls() 8
txtName = ""
txtAddress1 = ""
txtAddress2 = ""
txtCity = ""
txtState = ""
txtZipCode = ""
txtContact = ""
txtPhone = ""
End Sub
92
Private Sub cmdUpdate_Click() 9
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
-
8/8/2019 7 DB Access Using ADO&DataEnv
47/49
93
Private Function ValidData() As Boolean 10
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 IfIf Not ValidData Then
MsgBox strMessage, vbOKOnly, msDialogTitle
End If
End Function
94
Private Sub LoadRecord() 11
With mrsVendors
!VendorName = txtName
!VendorAddress1 = txtAddress1
!VendorAddress2 = txtAddress2
!VendorCity = txtCity
!VendorState = txtState
!VendorZipCode = txtZipCode
!VendorContact = txtContact
!VendorPhone = txtPhone
End With
End Sub
-
8/8/2019 7 DB Access Using ADO&DataEnv
48/49
95
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 TruetxtName.SetFocus
Exit Sub
ErrorHandler:
DisplayErrorMsg
End Sub
96
Private Sub txtName_Change() 13
SetNavigationButtons False
SetCommandButtons False
End Sub
Private Sub txtAddress1_Change()
SetNavigationButtons FalseSetCommandButtons False
End Sub
.
.
.
Private Sub txtPhone_Change()
SetNavigationButtons False
SetCommandButtons False
End Sub
-
8/8/2019 7 DB Access Using ADO&DataEnv
49/49
97
Private Sub Form_KeyDown(KeyCode As Integer, _ 14
Shift As Integer)
If KeyCode = vbKeyEscape Then
LoadControls
SetCommandButtons True
SetNavigationButtons True
End If
End Sub
Private Sub cmdExit_Click() 15
mrsVendors.Close
mcnAP.Close
Set mrsVendors = Nothing
Set mcnAP = Nothing
Unload frmVendors
End
End Sub
Private Sub DisplayErrorMsg() 16
MsgBox "Error Code: " & Err.Number & vbCrLf & _
"Description: " & Err.Description, _
vbOKOnly + vbCritical, msDialogTitle
End Sub
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 fullfunctionality
When unbound forms are best When the forms are relatively complex
When the user interface needs to work in a way that can't beaccomplished with bound forms
When you can't get the bound forms to do what you want them todo without serious debugging problems (see chapter 7)
Notes