Directory listing of http: uap.unnes.ac.id ebook biblebook Visual Basic 6 com & Library Books
12
C H A P T E R
Connecting to
a database
✦
✦
✦
✦
In This Cha pter
I
n this c hapter, I’m go ing to disc uss the ADO Connection
o bjec t in depth. Also , sinc e the Errors c o llec tio n and the
Error o bjec t are tightly c o upled with the Connection o bjec t,
I’m go ing to c o ver them also . Ac c ess to a data pro vider is managed using the ADO Connection o bjec t. Thus, every pro gram
that uses a database server must inc lude at least o ne
Connection o bjec t. Unless yo u are using multiple data
pro viders o r ac c essing multiple database servers, o ne
Connection o bjec t is suffic ient.
The Connection Object
The Connection o bjec t is used to maintain a c o nnec tio n to a
data so urc e. It c an be implic itly c reated thro ugh the Command
and Recordset o bjec ts, o r yo u c an c reate an instanc e o f the
Connection o bjec t and share it amo ng multiple Command and
Recordset o bjec ts.
Connection object properties
Table 12-1 lists the pro perties asso c iated with the
Connection o bjec t.
Using the ADO
Co nnectio n o bject
W o rking with the
ADO Erro r o bject
Intro ducing the ADO
Erro rs co llectio n
Co nnecting to yo ur
database server
Analyzing erro rs
✦
✦
✦
✦
212
Part II ✦ Beginning Database Programming
Table 12-1
Properties of the Connection Object
CrossReference
Property
Description
Attributes
A Long value containing the transaction attributes for a
connection (see Table 12-2). Note that not all data providers
support this property.
CommandTimeout
A Long containing the m axim um num ber of seconds for the
com m and to execute before an error is returned. Default is 30
seconds.
ConnectionString
A String containing the inform ation necessary to connect to
a data source.
ConnectionTimeout
A Long containing the m axim um num ber of seconds that the
program should w ait for a connection to be opened before
returning an error. Default is 15 seconds.
CursorLocation
A Long containing the default location of the cursor service
(see Table 12-3). This value w ill autom atically be inherited by
the Recordset object using this Connection object.
DefaultDatabase
A String containing the nam e of the default database.
Errors
An object reference to an Errors collection.
IsolationLevel
A Long containing the level of transaction isolation (see
Table 12-4).
Mode
A Long containing the available perm issions for m odifying data
(see Table 12-5).
Properties
An object reference to a Properties collection containing
provider-specific inform ation.
Provider
A String containing the nam e of the data provider. This value
m ay also be set as part of the ConnectionString.
State
A Long describing the current state of the Command object.
Multiple values can be com bined to describe the current state
(see Table 12-6).
Version
A String containing the current ADO version num ber.
See Chapter 22, “Integrating XML w ith Internet Explorer 5,” for m ore inform ation
about SQL Server connection strings; Chapter 26, “Overview of Oracle 8i,” for
m ore inform ation about Oracle 8i connection strings; and Chapter 30, “Creating
Jet Database Objects,” for m ore inform ation about Jet connection strings.
Chapter 12 ✦ Connecting to a database
Table 12-2
Values for Attributes
Constant
Value
Description
adXactCommitRetaining
131072
Calling CommitTrans autom atically
starts a new transaction.
adXactAbortRetaining
262144
Calling RollbackTrans autom atically
starts a new transaction.
Table 12-3
Values for CursorLocation
Constant
Value
Description
adUseNone
1
Does not use cursor services (obsolete).
adUseServer
2
Uses the server-side cursor library.
adUseClient
3
Uses the client-side cursor library.
Table 12-4
Values for IsolationLevel
Constant
Value
Description
adXactUnspecified
-1
The provider is using a different isolation
level than specified.
adXactChaos
16
Pending changes from m ore highly
isolated transactions can’t be overw ritten.
adXactBrowse
256
Can view uncom m itted changes in other
transactions.
adXactReadUncommitted
256
Sam e as adXactBrowse.
adXactCursorStability
4096
Can view only com m itted changes in
other transactions.
adXactReadCommitted
4096
Sam e as adXactCursorStability.
adXactRepeatableRead
65536
Can’t view changes in other transactions
until you Requery the Recordset
object.
Continued
213
214
Part II ✦ Beginning Database Programming
Table 12-4 (continued)
Constant
Value
Description
adXactIsolated
1048576
Transactions are conducted in isolation
from all other transactions.
adXactSerializable
1048576
Sam e as adXactIsolated.
Table 12-5
Values for M ode
Constant
Value
Description
adModeUnknown
0
Perm issions are not set or can’t be
determ ined.
adModeRead
1
Requests read perm ission.
adModeWrite
2
Requests w rite perm ission.
adModeReadWrite
3
Requests read/ w rite perm ission.
adModeShareDenyRead
4
Prevent other connections from opening
w ith read perm issions.
adModeShareDenyWrite
8
Prevent other connections from opening
w ith w rite perm issions.
adModeShareExclusive
12
Prevent other connections from opening.
adModeShareDenyNone
16
Perm it other connections w ith any
perm issions.
adModeRecursive
32
Used w ith adModeShareDenyRead,
adModeShareDenyWrite, and
adModeShareDenyNone to propagate
sharing restrictions to all sub-records of
the current Record.
Connection object methods
The Connection o bjec t has many metho ds that allo w yo u to manage yo ur c o nnec tio n to a data so urc e.
Chapter 12 ✦ Connecting to a database
Table 12-6
Values for State
Constant
Value
Description
adStateClosed
0
The Command object is closed.
adStateOpen
1
The Command object is open.
adStateConnecting
2
The Command object is connecting to the
database.
adStateExecuting
4
The Command object is executing.
adStateFetching
8
Row s are being retrieved.
Function BeginTrans ( ) As Long
The BeginTrans metho d marks the beginning o f a transac tio n. The return value
c o rrespo nds to the nesting level o f the transac tio n. The first c all to BeginTrans
will return a o ne. A sec o nd c all to BeginTrans, witho ut a c all to CommitTrans o r
RollbackTrans, will return two .
Sub Cancel ( )
The Cancel metho d is used to terminate an async hro no us task started by the
Execute o r Open metho ds.
Sub Close ( )
The Close metho d c lo ses the c o nnec tio n to the data pro vider. It will also c lo se any
o pen Recordset o bjec ts and set the ActiveConnection pro perty o f any Command
o bjec ts to Nothing.
Sub CommitTrans ( )
The CommitTrans metho d ends a transac tio n and saves the c hanges to the
database. Depending o n the Attributes pro perty, a new transac tio n may auto matic ally be started.
Function Execute (CommandText As String, [RecordsAffected],
[Options As Long = -1]) As Recordset
The Execute metho d is used to exec ute the spec ified c o mmand. A Recordset
o bjec t will be returned as the result o f the func tio n, whic h will c o ntain any ro ws
returned by the c o mmand.
215
216
Part II ✦ Beginning Database Programming
CommandText is a String c o ntaining an SQL Statement, sto red pro c edure, table
name, o r o ther data pro vider-spec ific c o mmand to be exec uted.
RecordsAffected o ptio nally returns a Long value with the number o f rec o rds
affec ted by the c o mmand.
Options o ptio nally passes a c o mbinatio n o f the values spec ified in Table 11-5 fo und
in the sec tio n o n the Command o bjec t.
Sub Open ([ConnectionString As String], [UserID As String],
[Password As String], [Options As Long = -1])
The Open metho d initializes the Connection o bjec t by establishing a c o nnec tio n to
a data pro vider.
ConnectionString is a String value c o ntaining the same c o nnec tio n info rmatio n
fo und in the ConnectionString pro perty. The value in this parameter will o verride
the value in the pro perty.
UserID c o ntains a String value with the UserID needed to ac c ess the database.
This value will o verride any UserID info rmatio n inc luded in the ConnectionString
parameter o r pro perty.
Password c o ntains a String value with the passwo rd asso c iated with the spec ified
UserID. This value will o verride any passwo rd info rmatio n inc luded in the
ConnectionString parameter o r pro perty.
Options o ptio nally passes o ne o f the values spec ified in Table 12-7. If yo u spec ify
adAsyncConnect, the ConnectComplete event will be fired when the c o nnec tio n
pro c ess has finished.
Table 12-7
Values for Options
Constant
Value
Description
adConnectUnspecified
-1
Opens the connection synchronously.
Default.
adAsyncConnect
16
Opens the connection asynchronously.
Chapter 12 ✦ Connecting to a database
Function OpenSchema (Schema As SchemaEnum,
[Restrictions], [SchemaID]) As Recordset
The OpenSchema metho d returns database info rmatio n fro m the data pro vider. A
Recordset o bjec t will be returned as the result o f the func tio n, whic h will c o ntain
any ro ws returned by the c o mmand.
Schema is an enumerated value spec ifying the type o f info rmatio n to be returned.
Restrictions c o ntains an array o f query c o nstraints.
SchemaID o ptio nally c o ntains a GUID fo r a pro vider-sc hema query no t defined in
the OLE DB spec ific atio n. This parameter is o nly used when the Schema parameter
is set to adSchemaProviderSpecific.
Note
So you want to write a database utility: The OpenSchema m ethod can be used
to perform nearly forty different queries against a database catalog. Each query
returns a different Recordset containing the relevant inform ation. Since this
inform ation is extrem ely com plex and not generally used by database program m ers, you should reference the OLE DB docum entation for detailed inform ation
about this m ethod.
Sub RollbackTrans ( )
The RollbackTrans metho d ends a transac tio n and disc ards any c hanges to the
datab ase. Depending o n the Attributes pro perty, a new transac tio n may auto matic ally b e started.
Connection object events
The Connection o bjec t c o ntains events that allo w yo u to interc ept status info rmatio n and determine erro r c o nditio ns while yo u have a c o nnec tio n to yo ur data so urc e.
Event BeginTransComplete (TransactionLevel As Long, pError As Error,
adStatus As EventStatusEnum, pConnection As Connection)
The BeginTransComplete is c alled after the BeginTrans metho d has finished
running in async hro no us mo de.
TransactionLevel is a Long value c o ntaining the new transac tio n level.
pError is an o bjec t referenc e to an Error o bjec t if the value o f adStatus is set to
adStatusErrorsOccured.
adStatus is a Long value that c o ntains o ne o f the status values listed in Table 12-8.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
BeginTrans metho d.
217
218
Part II ✦ Beginning Database Programming
Table 12-8
Values for adStatus
Constant
Value
Description
adStatusOK
1
The operation com pleted successfully.
adStatusErrorsOccured
2
The operation failed. Error inform ation is
in pError.
adStatusCantDeny
3
The operation can’t request the
cancellation of the current operation.
adStatusCancel
4
The operation requested that the
operation be canceled.
adStatusUnwantedEvent
5
Setting the value of the adStatus
param eter to this value w hile in the
event w ill prevent subsequent events
from being fired.
Event CommitTransComplete (pError As Error, adStatus As
EventStatusEnum, pConnection As Connection)
The CommitTransComplete is c alled when the CommitTrans metho d has finished
running in async hro no us mo de.
pError is an o bjec t referenc e to an Error o bjec t if the value o f adStatus is set to
adStatusErrorsOccured.
adStatus is a Long value that c o ntains o ne o f the status values listed in Table 12-8
in the BeginTransComplete event.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
CommitTrans metho d.
Event ConnectComplete (pError As Error, adStatus As
EventStatusEnum, pConnection As Connection)
The ConnectComplete is c alled when the Connect metho d has finished running in
async hro no us mo de.
pError is an o bjec t referenc e to an Error o bjec t if the value o f adStatus is set to
adStatusErrorsOccured.
Chapter 12 ✦ Connecting to a database
adStatus is a Long value that c o ntains o ne o f the status values listed in Table 12-8
in the BeginTransComplete event.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
Connect metho d.
Event Disconnect (adStatus As EventStatusEnum, pConnection
As Connection)
The Disconnect event is c alled when the c o nnec tio n has been dro pped fro m the
data so urc e.
adStatus is a Long value that always c o ntains adStatusOK.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
CommitTrans metho d.
Event ExecuteComplete (RecordsAffected As Long, pError As Error,
adStatus As EventStatusEnum, pCommand As Command, pRecordset As
Recordset, pConnection as Connection)
The ExecuteComplete event is c alled when the Execute metho d has finished running in async hro no us mo de.
RecordsAffected is a Long value c o ntaining the number o f rec o rds affec ted by the
c o mmand exec uted by the Execute metho d.
pError is an o bjec t referenc e to an Error o bjec t if the value o f adStatus is set to
adStatusErrorsOccured.
adStatus is a Long value c o ntaining o ne o f the status values listed in Table 12-8 in
the BeginTransComplete event.
pCommand is an o bjec t referenc e to a Command o bjec t, if a Command o bjec t was exec uted.
pRecordset is an o bjec t referenc e to a Recordset o bjec t c o ntaining the results o f
the c o mmand’s exec utio n.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
ExecuteComplete metho d.
219
220
Part II ✦ Beginning Database Programming
Event InfoM essage (pError As Error, adStatus As EventStatusEnum,
pConnection as Connection)
The InfoMessage event is c alled when a warning message is rec eived by the c urrent c o nnec tio n.
pError is an o bjec t referenc e to an Error o bjec t if the value o f adStatus is set to
adStatusErrorsOccured.
adStatus is a Long value c o ntaining o ne o f the status values listed in Table 12-8 in
the BeginTransComplete event.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
message.
Event RollbackTransComplete (pError As Error, adStatus As
EventStatusEnum, pConnection as Connection)
The RollbackTransComplete event is c alled when the RollbackTrans metho d
has finished running in async hro no us mo de.
pError is an o bjec t referenc e to an Error o bjec t if the value o f adStatus is set to
adStatusErrorsOccured.
adStatus is a Long value c o ntaining o ne o f the status values listed in Table 12-8 in
the BeginTransComplete event.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with
RollbackTrans metho d.
Event WillConnect (ConnectionString As String, UserID As String,
Password As String, Options As Long, adStatus As EventStatusEnum,
pConnection as Connection)
The WillConnect event is c alled befo re the pro c ess to establish that a c o nnec tio n
is started. Yo u c an o verride any o f the values in the ConnectionString, UserID,
Password, and Options pro perties. By default, the value o f adStatus is set to
adStatusOK. If yo u set adStatus to adStatusCancel, yo u will terminate the c o nnec tio n request. This will trigger the ConnectComplete event with an adStatus o f
adStatusErrorsOccurred.
ConnectionString is a String c o ntaining the same c o nnec tio n info rmatio n fo und
in the ConnectionString pro perty.
UserID c o ntains a String value with the UserID needed to ac c ess the database.
Chapter 12 ✦ Connecting to a database
Password c o ntains a String value with the passwo rd asso c iated with the spec ified
UserID.
Options o ptio nally passes o ne o f the values spec ified in Table 12-7 in the Open
metho d abo ve.
adStatus is a Long value c o ntaining o ne o f the status values listed in Table 12-8 in
the BeginTransComplete event.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
c o nnec tio n that triggered this event.
Event WillExecute (Source As String, CursorType As CursorTypeEnum,
LockType As LockTypeEnum, Options As Long, adStatus As EventStatus
Enum, pCommand As Command, pRecordset As Recordset, pConnection
as Connection)
The WillExecute event is c alled befo re a c o mmand is exec uted. Yo u c an o verride
any o f the values in the Source, CursorType, LockType and Options pro perties.
By default, the value o f adStatus is set to adStatusOK. If yo u set adStatus to
adStatusCancel, yo u will terminate the c o nnec tio n request. This will trigger the
ConnectComplete event with an adStatus o f adStatusErrorsOccurred.
Source is a String c o ntaining the SQL Statement, sto red pro c edure name, o r o ther
c o mmand to be exec uted.
CursorType c o ntains a CursorTypeEnum value desc ribing the type o f c urso r to be
used in the Recordset (see Table 12-9).
LockType c o ntains a LockTypeEnum value (see Table 12-10).
Options o ptio nally passes o ne o f the values spec ified in Table 12-7 in the Open
metho d abo ve.
adStatus is a Long value c o ntaining o ne o f the status values listed in Table 12-7 in
the BeginTransComplete event.
pCommand is an o bjec t referenc e to a Command o bjec t, if a Command o bjec t is abo ut
to be exec uted.
pRecordset is an o bjec t referenc e to a Recordset o bjec t, if a Recordset o bjec t
was the so urc e o f the func tio n to be exec uted.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
c o nnec tio n that triggered this event.
221
222
Part II ✦ Beginning Database Programming
Table 12-9
Values for CursorType
Constant
Value
Description
adOpenUnspecified
-1
The type of cursor isn’t specified.
adOpenForwardOnly
0
A forw ard-only cursor is used, w hich perm its
you only to scroll forw ard through the records
in the Recordset.
adOpenKeyset
1
A keyset cursor is used, w hich is sim ilar to a
dynam ic cursor, but doesn’t perm it you to see
records added by other users.
adOpenDynamic
2
A dynam ic cursor is used, w hich allow s you to
see records added by other users, plus any
changes and deletions m ade by other users.
adOpenStatic
3
A static cursor is used, w hich prevents you
from seeing any and all changes from other
users.
Table 12-10
Values for LockType
Constant
Value
Description
adLockUnspecified
-1
The type of locking isn’t specified.
adLockReadOnly
1
Doesn’t perm it you to change any values.
adLockPessimistic
2
Records are locked at the data source record
by record once the data in the record has
been changed.
adLockOptimistic
3
Records are locked only w hen you call the
UpdateMethod.
adLockBatchOptimistic
4
Records are not locked, and conflicts w ill be
returned for resolution after the
UpdateBatch m ethod has com pleted.
Chapter 12 ✦ Connecting to a database
The Error Object
The Error o bjec t c o ntains info rmatio n abo ut a spec ific erro r c o nditio n.
Error object properties
Table 12-11 lists the pro perties asso c iated with the Error o bjec t.
Table 12-11
Properties of the Error Object
Property
Description
Description
A String value containing a short text description of the error.
HelpContext
A Long value containing the help context ID reference w ithin the
help file specified by HelpFile. If no additional help can be
found, this value w ill contain a zero.
HelpFile
A String containing the nam e of the help file w here a m ore
detailed description of the error m ay be found. If no additional
help is available, this value w ill contain an em pty string.
NativeError
A Long containing a provider-specific error code.
Number
A Long containing the OLE DB error code num ber. This value is
unique to this specific error condition.
Source
A String containing the nam e of the object or application that
caused the error. ADO errors w ill generally have Source values of
the form at ADODB.objectname, ADOX.objectname, or ADOMD.
objectname, w here objectname is the nam e of the object that
caused the error.
SQLState
A String containing the standard five-character ANSI SQL
error code.
The Errors Collection
The Errors c o llec tio n c o ntains the set o f erro rs generated in respo nse to a spec ific
failure. If an o peratio n fails, the Errors c o llec tio n is c leared and all o f the individual
erro rs are rec o rded in the c o llec tio n.
223
224
Part II ✦ Beginning Database Programming
If yo u are using the Resync, UpdateBatch, o r CancelBatch metho ds o n a
Recordset o bjec t, yo u may generate a set o f warnings that will no t raise the On
Error c o nditio n in Visual Basic . Thus, it is impo rtant to c hec k fo r warnings when
using these metho ds and take the appro priate ac tio n.
Caution
I’m certain it didn’t error again: Successfully perform ing a function w ill not clear
the Errors collection. Thus, the inform ation from a previous error w ill rem ain in
the collection until it is either explicitly cleared or another error occurs. For this
reason, it is very im portant that you clear the Errors collection after you handle
the error condition and before you resum e norm al processing. Otherw ise, you
m ay falsely detect an error condition.
Errors collection properties
Table 12-12 lists the pro perties asso c iated with the Errors c o llec tio n.
Table 12-12
Properties of the Errors Collection
Property
Description
Count
A Long value containing the num ber of errors in the collection.
Item(index)
An object reference to an Error object containing inform ation about a
particular error. To locate an error, specify a value in the range of 0 to
Count –1.
Errors collection methods
The Errors c o llec tio n c o ntains metho ds to manage the c o llec tio n o f erro r
info rmatio n.
Sub Clear ( )
The Clear metho d initializes the Errors c o llec tio n to the empty state.
Sub Refresh ( )
The Refresh metho d gets a fresh c o py o f the erro r info rmatio n fro m the data
pro vider.
Chapter 12 ✦ Connecting to a database
Connecting To Database Server
In the previo us c hapters, I pro vided all o f the info rmatio n nec essary to c o nnec t to
either the ADO Data Co ntro l o r the Data Enviro nment Designer and they to o k c are
o f c o nnec ting to the database server. Ho wever, if yo u plan to use the ADO o bjec ts
direc tly, yo u need to deal with a few issues yo urself.
Connection strings
A co nne ctio n string c o ntains the info rmatio n nec essary to c o nnec t yo ur applic atio n
to a data so urc e. This value is sto red in the ConnectionString pro perty o f the
Connection o bjec t. It c o nsists o f a series o f keywo rd c lauses separated by semic o lo ns (;). Yo u c reate a keywo rd c lause by spec ifying a keywo rd, an equal sign (=),
and then the value o f the keywo rd. If the same keywo rd is spec ified mo re than o nc e,
o nly the last o c c urrenc e will be used, exc ept in the c ase o f the provider keywo rd,
in whic h the first o c c urrenc e will be used.
Note
Spaces are permitted: A keyw ord alw ays ends w ith an equal sign, so special
characters, such as a space or a period, are legal.
Co nsider the fo llo wing c o nnec tio n string:
provider=sqloledb;data source=Athena;initial catalog=VB6DB
It uses the sqloledb pro vider and then spec ifies Athena as the data so urc e and
VB6DB as the initial c atalo g. No te the spac es inside bo th the data so urc e and the initial c atalo g keywo rds are legal.
Tip
Connection strings the easy way: Building a connection string to a new database
system can be a real headache, m aking sure that you have all the needed keyw ords to m ake the connection. Try building a dum m y application using the ADO
Data Control. Then configure the ConnectionString property using the
Properties dialog box. This creates the connection string and puts it in the
ConnectionString property. Then all you need to do is copy the connection
string to your application.
Provider keyword
The Provider keywo rd spec ifies the name o f the OLE DB pro vider that will be
used to c o nnec t to the data so urc e. If this keywo rd is no t inc luded in the c o nnec tio n string, the OLD DB Provider for ODBC will be used. Table 12-13 lists so me
c o mmo n databases and their OLE DB pro viders.
225
226
Part II ✦ Beginning Database Programming
Table 12-13
Common OLE DB Providers
Database
Provider
OLE DB Provider for ODBC
MSDASQL.1
Jet 3.51 (Access 97)
Microsoft.Jet.OLEDB.3.51
Jet 4.0 (Access 2000)
Microsoft.Jet.OLEDB.4.0
Oracle
MSDAORA.1
SQL Server 7
SQLOLEDB
Common keywords
Nearly all data pro viders suppo rt the keywo rds listed in Table 12-14. In many c ases,
these keywo rds will be all yo u need to c o nnec t to the data so urc e.
Table 12-14
Common Keywords for SQLOLEDB
Keyword
Alias
Description
Data Source
Server
Specifies the location of the database server or the
nam e of the file containing the data, depending on
the specific provider.
Initial Catalog
Database
Specifies the nam e of the default database on the
database server.
Password
PWD
Specifies the passw ord associated w ith the User Id
keyw ord.
User Id
UID
Specifies the user nam e that w ill be used to connect
to the database server.
Keywords for SQLOLEDB
Ac c essing an SQL Server database is very straightfo rward. All yo u need to do is
inc lude the Data Source keywo rd and either spec ify the user name and passwo rd
o r set the Trusted_Connection keywo rd to yes. Ho wever, there are a number o f
o ther keywo rds that c an pro vide additio nal func tio ns. Table 12-15 lists the set o f
keywo rds that are spec ific to SQL Server.
Chapter 12 ✦ Connecting to a database
Table 12-15
Common Keywords for SQLOLEDB
Keyword
Description
Application Name
Contains the nam e of the application program .
Connect Timeout
Specifies the num ber of seconds in w hich the database
server m ust respond before the connection w ill tim eout.
Integrated Security
When set to SSPI, Window s NT Authentication w ill be
used.
Trusted_Connection
Contains yes if you are using Window s NT
Authentication.
Workstation ID
Contains nam e of the client m achine.
Keywords for M icrosoft.Jet.OLEDB.4.0
When ac c essing a Jet database, yo u need to remember that there isn’t really a
database server invo lved, like there is with mo st o ther database systems. The
database is a spec ially fo rmatted disk file, whic h yo u referenc e in the Data Source
keywo rd. The o ther keywo rds have the no rmal meaning, and the list o f spec ific keywo rds fo r the Mic ro so ft Jet pro vider is listed in Table 12-16.
Table 12-16
Common Keywords for SQLOLEDB
Keyword
Description
Jet OLEDB:System Database
Contains the fully qualified file nam e for the
w orkgroup inform ation file.
Jet OLEDB:Registry Path
Specifies the registry key that contains values for
the database engine.
Jet OLEDB:Database Password
Contains the database passw ord.
Opening a connection
Opening a database c o nnec tio n is merely a matter o f dec laring an o bjec t, c reating a
new instanc e o f it, and then o pening the c o nnec tio n. The key is using the pro per
c o nnec tio n string when yo u o pen the c o nnec tio n.
227
228
Part II ✦ Beginning Database Programming
Declaring a Connection object
The fo llo wing line o f c o de dec lares the variable db as a Connection o bjec t.
Dim db As ADODB.Connection
Yo u c an use any o f the metho ds o r pro perties asso c iated with the Connection
o bjec t, but no t any o f the events. This is perfec tly fine fo r mo st pro grams. The
events o nly pro vide status info rmatio n that c an be safely igno red by mo st pro grams.
Tip
Globally speaking: When creating applications w ith m ultiple form s, I often add a
m odule to the program to hold objects that I w ant to access, including things like
the Connection object, w hich can easily share am ong m ultiple form s.
So metimes, ho wever, yo u might want to trac k this status info rmatio n. This is a great
plac e to inc lude extra sec urity c hec ks, sinc e yo u have the o ppo rtunity to review vario us func tio ns befo re they are ac tually perfo rmed, and c anc el them. To inc lude events
with the Connection o bjec t, yo u need to use the WithEvents keywo rd in the Dim
statement as in the statement belo w:
Dim WithEvents db As ADODB.Connection
Note
Qualifying for clarity: I usually use the ADODB prefix for all ADO objects. This elim inates confusion w ith other objects (such as the DAO) that have the sam e nam e.
The WithEvents keywo rd impo ses so me restric tio ns o n ho w yo u c an dec lare yo ur
o bjec t. Yo u c an o nly use it in Form mo dules and Class mo dules. Yo u c an’t use it in
a regular .BAS mo dule. Yo u also c an’t use the New keywo rd. Yo u must instantiate
the o bjec t using a Set statement with the New keywo rd.
Tip
Faster objects: While you can use the New keyw ord in a Dim statem ent to create
an object the first tim e it’s used, it adds code to every statem ent to see if the
object exists and create it if necessary.
Coding the Connection object
One o f the things I like best abo ut using the ADO o bjec ts direc tly, rather than using
the Data Enviro nment Designer o r the ADO Data Co mmand, is that the database
isn’t o pened fo r me when the pro gram is started. This allo ws me the o ppo rtunity
to ask the user fo r their user name and passwo rd befo re I o pen the database.
The Co nnec t Demo pro gram sho wn in Figure 12-1 is a very simple pro gram that
demo nstrates ho w to c o nnec t to an SQL Server database. It c o nsists o f two c o mmand butto ns that are used to c o nnec t and disc o nnec t fro m the database, plus two
text bo xes that allo w the user to enter their user name and passwo rd.
Chapter 12 ✦ Connecting to a database
Figure 12-1: The Connect Dem o program
Clic king the butto n labeled Co nnec t will fire the Command1_Click event, as sho wn
in Listing 12-1. I begin the ro utine by using the On Error Resume Next statement,
whic h prevents a run-time erro r fro m killing the pro gram. Ho wever, I need to be
c areful to explic itly c hec k fo r erro r c o nditio ns, o r an undetec ted erro r c o uld c ause
havo c with my pro gram.
Listing 12-1: The Command1_Click event in Connect Demo
Private Sub Command1_Click()
Dim p As ADODB.Property
On Error Resume Next
Set db = New ADODB.Connection
db.ConnectionString = “provider=sqloledb;” & _
“data source=Athena;initial catalog=VB6DB”
db.Properties(“User Id”).Value = Text1.Text
db.Properties(“Password”).Value = Text2.Text
db.Open
Continued
229
230
Part II ✦ Beginning Database Programming
Listing 12-1 (continued)
If db.State = adStateOpen Then
Command1.Enabled = False
Command2.Enabled = True
Else
WriteError
End If
End Sub
Next, I c reate a new instanc e o f the Connection o bjec t using the Set statement.
Then I set the vario us pro perties in the Connection befo re I o pen the c o nnec tio n.
While I c an set the ConnectionString pro perty direc tly, I need to set the values
fo r User Id and Password thro ugh the Properties c o llec tio n. Fo r these values, I
simply use the name o f the pro perty as the index in the Properties c o llec tio n and
assign the values I want to the Value pro perty. Of c o urse, these pro perties are spec ific to the pro vider that is used, so yo u need to see whic h o f these c usto m pro perties yo u really need.
CrossReference
Check “The Param eter Object” and “The Param eters Collection” in Chapter 13 for
m ore details about these objects.
Opening the connection
Onc e the pro perties are set, I invo ke the Open metho d to c o nnec t to the database
server. Ano ther way to handle the c o nnec tio n wo uld be to spec ify all o f the info rmatio n as part o f the c all to the Open metho d, as sho wn belo w:
db.Open “provider=sqloledb;data source=Athena; “ & _
“initial catalog=VB6DB”, Text1.Text, Text2.Text
This has the advantage o f fewer lines o f text, whic h means fewer plac es where
so mething c an go wro ng.
After I’ve used the Open metho d, I need to kno w if it was suc c essful. Had I no t used
the On Error statement, I c o uld safely assume that the Open metho d was suc c essful,
bec ause the pro gram wo uld had go tten a run-time erro r and died. Here I c an do o ne
o f two things. First, I c an c hec k the Errors o bjec t to see if there was an erro r and
c hec k the erro r c o de fo r the appro priate ac tio n. Sec o nd, I c an c hec k the State pro perty to make sure that the o bjec t’s state is o pen. If the c o nnec tio n is o pen, I’ll disable
the butto n that c o nnec ts to the database and enable the butto n that c lo ses the c o nnec tio n. If it isn’t, I’ll display an erro r message to the user with the WriteError
ro utine.
Chapter 12 ✦ Connecting to a database
Closing a connection
Clo sing a Connection o bjec t is merely a matter o f using the Close metho d and
releasing the reso urc es asso c iated with the o bjec t, whic h yo u c an see in Listing
12-2. If I was able to c lo se the c o nnec tio n, I will disable the Disc o nnec t butto n and
reenable the Co nnec t butto n so the user c an try c o nnec ting to the database again.
If the Close metho d generated an erro r, I’ll display the erro r using the WriteError
ro utine.
Listing 12-2: The Command2_Click event in Connect Demo
Private Sub Command2_Click()
db.Close
If db.State = adStateClosed Then
Set db = Nothing
Command2.Enabled = False
Command1.Enabled = True
Else
WriteError
End If
End Sub
Analyzing Errors
The Connection o bjec t’s Errors c o llec tio n c o ntains the info rmatio n abo ut the
mo st rec ent erro r that o c c urred. When perfo rming database func tio ns, it is quite
po ssible that a single request may generate multiple erro rs. Usually, the first erro r
is the mo st signific ant erro r, and the rest o f the erro rs are sec o ndary effec ts o f the
main erro r.
Retrieving erro r info rmatio nThe WriteError subro utine in Listing 12-3 is designed
to update a StatusBar c o ntro l with the results o f the mo st rec ent erro r. I c hec k the
Count pro perty to see ho w many erro rs are in the c o llec tio n, and if there’s o nly
o ne, I display it in the status bar. If I have multiple erro rs, I’ll display the first erro r
in the status bar just like I displayed the single erro r, and then use a For Each lo o p
to display eac h o f the individual erro r messages.
231
232
Part II ✦ Beginning Database Programming
Listing 12-3: The WriteError subroutine in Connect Demo
Private Sub WriteError()
Dim e As ADODB.Error
If db.Errors.Count = 1 Then
StatusBar1.SimpleText = “Error: “ & db.Errors(0).Description
Elseif db.Errors.Count > 1 Then
StatusBar1.SimpleText = “Multiple errors:” & _
db.Errors(0).Description
For Each e In db.Errors
MsgBox e.Description
Next e
End If
db.Errors.Clear
End Sub
It is impo rtant to c lear the Errors c o llec tio n befo re yo u issue the next database
request. The Errors c o llec tio n is o nly c leared auto matic ally the next time an erro r
is enc o untered. If yo u do n’t c lear the c o llec tio n befo re yo u issue a database request,
and then c hec k it afterwards, yo u c an’t be c ertain that the erro rs in the Errors c o llec tio n were c aused by the mo st rec ent database request.
There are two plac es where yo u sho uld c lear the Errors c o llec tio n. The first is
immediately after handling an erro r c o nditio n, as I did in the WriteError ro utine.
This ensures that Error o bjec t is c lear after pro c essing an erro r c o nditio n. Ho wever,
sinc e it is po ssible that yo u may no t c hec k every plac e there c an be an erro r, yo u
sho uld also c lear the Errors c o llec tio n befo re any c all that might result in an erro r.
Watching connection activity
The events asso c iated with the Connect o bjec t pro vide a way to c atc h an ac tivity
befo re and after it exec utes. This will allo w yo u to grab info rmatio n and display it to
the user, o r to review the request and deny it.
Displaying status information
The db_ConnectComplete event sho wn in Listing 12-4 will be fired after the user
c o nnec ts to the database. I begin by c hec king the adStatus parameter to see if the
Chapter 12 ✦ Connecting to a database
c o nnec tio n c o mpleted witho ut an erro r. If it did, I let the user kno w that they’re
c o nnec ted to the database. Otherwise, I get the erro r message fro m the pError
o bjec t and display it in the status bar.
Listing 12-4: The db_ConnectComplete event in Connect Demo
Private Sub db_ConnectComplete(ByVal pError As ADODB.Error, _
adStatus As ADODB.EventStatusEnum, _
ByVal pConnection As ADODB.Connection)
If adStatus = adStatusOK Then
StatusBar1.SimpleText = “Connected.”
Else
StatusBar1.SimpleText = “Error: “ & pError.Description
End If
End Sub
Canceling a request
The Complete events in the Co nnec tio n o bjec t merely indic ate the c urrent status o f
a request. The Will events, o n the o ther hand, are the perfec t plac e to review a
request and c anc el it if desired. Listing 12-5 takes advantage o f the db_WillConnect
event to see if the user really wants to c o nnec t to the database server.
Listing 12-5: The db_WillConnect event in Connect Demo
Private Sub db_WillConnect(ConnectionString As String, _
UserID As String, Password As String, Options As Long, _
adStatus As ADODB.EventStatusEnum, _
ByVal pConnection As ADODB.Connection)
If MsgBox(“Do you really want to connect?”, vbYesNo, _
“Connect to remote database”) = vbYes Then
StatusBar1.SimpleText = “Will connect.”
Else
adStatus = adStatusCancel
End If
End Sub
233
234
Part II ✦ Beginning Database Programming
I begin this ro utine by displaying a message bo x that asks the user if they really
want to c o nnec t to the database server. If the user respo nds no , I’ll c anc el the
request by setting the adStatus parameter to adStatusCancel. This will trigger
an erro r c o nditio n, whic h is interc epted by bo th the WriteError ro utine and the
ConnectComplete event. If the user respo nds yes, the status bar is updated, and
the Open metho d will be allo wed to c o ntinue.
Tip
So it’s contrived: The exam ple here is som ew hat contrived; how ever, in a real
application, you m ay w ant to restrict connections based on the tim e of date, day of
w eek, or particular value of the user nam e.
Thoughts on the Connection Object
The Connection object m anages the path to your database server. In m ost cases, you’ll
open the connection w hen your program begins and close it w hen it ends. You w on’t
bother w ith any of the events and you m ay not even specify any of the connection properties other than the connection string. After all, the m ain reason you w ant to use the
Connection object is to connect to the database. The real w ork of your application w ill be
done w ith the other objects in the ADO library.
Summary
In this c hapter yo u learned the fo llo wing:
✦ Yo u c an use the Connection o bjec t to establish a link between the database
c lient pro gram and the database server.
✦ Yo u c an use c o nnec tio n strings to spec ify the parameters that are passed to
the OLE DB pro vider to establish the c o nnec tio n to the database server.
✦ Yo u c an use the Error o bjec t to determine why the mo st rec ent database
request failed.
✦ Yo u c an use the events in the Connection o bjec t to gather info rmatio n abo ut
the vario us database requests sent to the database server and c anc el them if
desired.
✦
✦
✦
C H A P T E R
Connecting to
a database
✦
✦
✦
✦
In This Cha pter
I
n this c hapter, I’m go ing to disc uss the ADO Connection
o bjec t in depth. Also , sinc e the Errors c o llec tio n and the
Error o bjec t are tightly c o upled with the Connection o bjec t,
I’m go ing to c o ver them also . Ac c ess to a data pro vider is managed using the ADO Connection o bjec t. Thus, every pro gram
that uses a database server must inc lude at least o ne
Connection o bjec t. Unless yo u are using multiple data
pro viders o r ac c essing multiple database servers, o ne
Connection o bjec t is suffic ient.
The Connection Object
The Connection o bjec t is used to maintain a c o nnec tio n to a
data so urc e. It c an be implic itly c reated thro ugh the Command
and Recordset o bjec ts, o r yo u c an c reate an instanc e o f the
Connection o bjec t and share it amo ng multiple Command and
Recordset o bjec ts.
Connection object properties
Table 12-1 lists the pro perties asso c iated with the
Connection o bjec t.
Using the ADO
Co nnectio n o bject
W o rking with the
ADO Erro r o bject
Intro ducing the ADO
Erro rs co llectio n
Co nnecting to yo ur
database server
Analyzing erro rs
✦
✦
✦
✦
212
Part II ✦ Beginning Database Programming
Table 12-1
Properties of the Connection Object
CrossReference
Property
Description
Attributes
A Long value containing the transaction attributes for a
connection (see Table 12-2). Note that not all data providers
support this property.
CommandTimeout
A Long containing the m axim um num ber of seconds for the
com m and to execute before an error is returned. Default is 30
seconds.
ConnectionString
A String containing the inform ation necessary to connect to
a data source.
ConnectionTimeout
A Long containing the m axim um num ber of seconds that the
program should w ait for a connection to be opened before
returning an error. Default is 15 seconds.
CursorLocation
A Long containing the default location of the cursor service
(see Table 12-3). This value w ill autom atically be inherited by
the Recordset object using this Connection object.
DefaultDatabase
A String containing the nam e of the default database.
Errors
An object reference to an Errors collection.
IsolationLevel
A Long containing the level of transaction isolation (see
Table 12-4).
Mode
A Long containing the available perm issions for m odifying data
(see Table 12-5).
Properties
An object reference to a Properties collection containing
provider-specific inform ation.
Provider
A String containing the nam e of the data provider. This value
m ay also be set as part of the ConnectionString.
State
A Long describing the current state of the Command object.
Multiple values can be com bined to describe the current state
(see Table 12-6).
Version
A String containing the current ADO version num ber.
See Chapter 22, “Integrating XML w ith Internet Explorer 5,” for m ore inform ation
about SQL Server connection strings; Chapter 26, “Overview of Oracle 8i,” for
m ore inform ation about Oracle 8i connection strings; and Chapter 30, “Creating
Jet Database Objects,” for m ore inform ation about Jet connection strings.
Chapter 12 ✦ Connecting to a database
Table 12-2
Values for Attributes
Constant
Value
Description
adXactCommitRetaining
131072
Calling CommitTrans autom atically
starts a new transaction.
adXactAbortRetaining
262144
Calling RollbackTrans autom atically
starts a new transaction.
Table 12-3
Values for CursorLocation
Constant
Value
Description
adUseNone
1
Does not use cursor services (obsolete).
adUseServer
2
Uses the server-side cursor library.
adUseClient
3
Uses the client-side cursor library.
Table 12-4
Values for IsolationLevel
Constant
Value
Description
adXactUnspecified
-1
The provider is using a different isolation
level than specified.
adXactChaos
16
Pending changes from m ore highly
isolated transactions can’t be overw ritten.
adXactBrowse
256
Can view uncom m itted changes in other
transactions.
adXactReadUncommitted
256
Sam e as adXactBrowse.
adXactCursorStability
4096
Can view only com m itted changes in
other transactions.
adXactReadCommitted
4096
Sam e as adXactCursorStability.
adXactRepeatableRead
65536
Can’t view changes in other transactions
until you Requery the Recordset
object.
Continued
213
214
Part II ✦ Beginning Database Programming
Table 12-4 (continued)
Constant
Value
Description
adXactIsolated
1048576
Transactions are conducted in isolation
from all other transactions.
adXactSerializable
1048576
Sam e as adXactIsolated.
Table 12-5
Values for M ode
Constant
Value
Description
adModeUnknown
0
Perm issions are not set or can’t be
determ ined.
adModeRead
1
Requests read perm ission.
adModeWrite
2
Requests w rite perm ission.
adModeReadWrite
3
Requests read/ w rite perm ission.
adModeShareDenyRead
4
Prevent other connections from opening
w ith read perm issions.
adModeShareDenyWrite
8
Prevent other connections from opening
w ith w rite perm issions.
adModeShareExclusive
12
Prevent other connections from opening.
adModeShareDenyNone
16
Perm it other connections w ith any
perm issions.
adModeRecursive
32
Used w ith adModeShareDenyRead,
adModeShareDenyWrite, and
adModeShareDenyNone to propagate
sharing restrictions to all sub-records of
the current Record.
Connection object methods
The Connection o bjec t has many metho ds that allo w yo u to manage yo ur c o nnec tio n to a data so urc e.
Chapter 12 ✦ Connecting to a database
Table 12-6
Values for State
Constant
Value
Description
adStateClosed
0
The Command object is closed.
adStateOpen
1
The Command object is open.
adStateConnecting
2
The Command object is connecting to the
database.
adStateExecuting
4
The Command object is executing.
adStateFetching
8
Row s are being retrieved.
Function BeginTrans ( ) As Long
The BeginTrans metho d marks the beginning o f a transac tio n. The return value
c o rrespo nds to the nesting level o f the transac tio n. The first c all to BeginTrans
will return a o ne. A sec o nd c all to BeginTrans, witho ut a c all to CommitTrans o r
RollbackTrans, will return two .
Sub Cancel ( )
The Cancel metho d is used to terminate an async hro no us task started by the
Execute o r Open metho ds.
Sub Close ( )
The Close metho d c lo ses the c o nnec tio n to the data pro vider. It will also c lo se any
o pen Recordset o bjec ts and set the ActiveConnection pro perty o f any Command
o bjec ts to Nothing.
Sub CommitTrans ( )
The CommitTrans metho d ends a transac tio n and saves the c hanges to the
database. Depending o n the Attributes pro perty, a new transac tio n may auto matic ally be started.
Function Execute (CommandText As String, [RecordsAffected],
[Options As Long = -1]) As Recordset
The Execute metho d is used to exec ute the spec ified c o mmand. A Recordset
o bjec t will be returned as the result o f the func tio n, whic h will c o ntain any ro ws
returned by the c o mmand.
215
216
Part II ✦ Beginning Database Programming
CommandText is a String c o ntaining an SQL Statement, sto red pro c edure, table
name, o r o ther data pro vider-spec ific c o mmand to be exec uted.
RecordsAffected o ptio nally returns a Long value with the number o f rec o rds
affec ted by the c o mmand.
Options o ptio nally passes a c o mbinatio n o f the values spec ified in Table 11-5 fo und
in the sec tio n o n the Command o bjec t.
Sub Open ([ConnectionString As String], [UserID As String],
[Password As String], [Options As Long = -1])
The Open metho d initializes the Connection o bjec t by establishing a c o nnec tio n to
a data pro vider.
ConnectionString is a String value c o ntaining the same c o nnec tio n info rmatio n
fo und in the ConnectionString pro perty. The value in this parameter will o verride
the value in the pro perty.
UserID c o ntains a String value with the UserID needed to ac c ess the database.
This value will o verride any UserID info rmatio n inc luded in the ConnectionString
parameter o r pro perty.
Password c o ntains a String value with the passwo rd asso c iated with the spec ified
UserID. This value will o verride any passwo rd info rmatio n inc luded in the
ConnectionString parameter o r pro perty.
Options o ptio nally passes o ne o f the values spec ified in Table 12-7. If yo u spec ify
adAsyncConnect, the ConnectComplete event will be fired when the c o nnec tio n
pro c ess has finished.
Table 12-7
Values for Options
Constant
Value
Description
adConnectUnspecified
-1
Opens the connection synchronously.
Default.
adAsyncConnect
16
Opens the connection asynchronously.
Chapter 12 ✦ Connecting to a database
Function OpenSchema (Schema As SchemaEnum,
[Restrictions], [SchemaID]) As Recordset
The OpenSchema metho d returns database info rmatio n fro m the data pro vider. A
Recordset o bjec t will be returned as the result o f the func tio n, whic h will c o ntain
any ro ws returned by the c o mmand.
Schema is an enumerated value spec ifying the type o f info rmatio n to be returned.
Restrictions c o ntains an array o f query c o nstraints.
SchemaID o ptio nally c o ntains a GUID fo r a pro vider-sc hema query no t defined in
the OLE DB spec ific atio n. This parameter is o nly used when the Schema parameter
is set to adSchemaProviderSpecific.
Note
So you want to write a database utility: The OpenSchema m ethod can be used
to perform nearly forty different queries against a database catalog. Each query
returns a different Recordset containing the relevant inform ation. Since this
inform ation is extrem ely com plex and not generally used by database program m ers, you should reference the OLE DB docum entation for detailed inform ation
about this m ethod.
Sub RollbackTrans ( )
The RollbackTrans metho d ends a transac tio n and disc ards any c hanges to the
datab ase. Depending o n the Attributes pro perty, a new transac tio n may auto matic ally b e started.
Connection object events
The Connection o bjec t c o ntains events that allo w yo u to interc ept status info rmatio n and determine erro r c o nditio ns while yo u have a c o nnec tio n to yo ur data so urc e.
Event BeginTransComplete (TransactionLevel As Long, pError As Error,
adStatus As EventStatusEnum, pConnection As Connection)
The BeginTransComplete is c alled after the BeginTrans metho d has finished
running in async hro no us mo de.
TransactionLevel is a Long value c o ntaining the new transac tio n level.
pError is an o bjec t referenc e to an Error o bjec t if the value o f adStatus is set to
adStatusErrorsOccured.
adStatus is a Long value that c o ntains o ne o f the status values listed in Table 12-8.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
BeginTrans metho d.
217
218
Part II ✦ Beginning Database Programming
Table 12-8
Values for adStatus
Constant
Value
Description
adStatusOK
1
The operation com pleted successfully.
adStatusErrorsOccured
2
The operation failed. Error inform ation is
in pError.
adStatusCantDeny
3
The operation can’t request the
cancellation of the current operation.
adStatusCancel
4
The operation requested that the
operation be canceled.
adStatusUnwantedEvent
5
Setting the value of the adStatus
param eter to this value w hile in the
event w ill prevent subsequent events
from being fired.
Event CommitTransComplete (pError As Error, adStatus As
EventStatusEnum, pConnection As Connection)
The CommitTransComplete is c alled when the CommitTrans metho d has finished
running in async hro no us mo de.
pError is an o bjec t referenc e to an Error o bjec t if the value o f adStatus is set to
adStatusErrorsOccured.
adStatus is a Long value that c o ntains o ne o f the status values listed in Table 12-8
in the BeginTransComplete event.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
CommitTrans metho d.
Event ConnectComplete (pError As Error, adStatus As
EventStatusEnum, pConnection As Connection)
The ConnectComplete is c alled when the Connect metho d has finished running in
async hro no us mo de.
pError is an o bjec t referenc e to an Error o bjec t if the value o f adStatus is set to
adStatusErrorsOccured.
Chapter 12 ✦ Connecting to a database
adStatus is a Long value that c o ntains o ne o f the status values listed in Table 12-8
in the BeginTransComplete event.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
Connect metho d.
Event Disconnect (adStatus As EventStatusEnum, pConnection
As Connection)
The Disconnect event is c alled when the c o nnec tio n has been dro pped fro m the
data so urc e.
adStatus is a Long value that always c o ntains adStatusOK.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
CommitTrans metho d.
Event ExecuteComplete (RecordsAffected As Long, pError As Error,
adStatus As EventStatusEnum, pCommand As Command, pRecordset As
Recordset, pConnection as Connection)
The ExecuteComplete event is c alled when the Execute metho d has finished running in async hro no us mo de.
RecordsAffected is a Long value c o ntaining the number o f rec o rds affec ted by the
c o mmand exec uted by the Execute metho d.
pError is an o bjec t referenc e to an Error o bjec t if the value o f adStatus is set to
adStatusErrorsOccured.
adStatus is a Long value c o ntaining o ne o f the status values listed in Table 12-8 in
the BeginTransComplete event.
pCommand is an o bjec t referenc e to a Command o bjec t, if a Command o bjec t was exec uted.
pRecordset is an o bjec t referenc e to a Recordset o bjec t c o ntaining the results o f
the c o mmand’s exec utio n.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
ExecuteComplete metho d.
219
220
Part II ✦ Beginning Database Programming
Event InfoM essage (pError As Error, adStatus As EventStatusEnum,
pConnection as Connection)
The InfoMessage event is c alled when a warning message is rec eived by the c urrent c o nnec tio n.
pError is an o bjec t referenc e to an Error o bjec t if the value o f adStatus is set to
adStatusErrorsOccured.
adStatus is a Long value c o ntaining o ne o f the status values listed in Table 12-8 in
the BeginTransComplete event.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
message.
Event RollbackTransComplete (pError As Error, adStatus As
EventStatusEnum, pConnection as Connection)
The RollbackTransComplete event is c alled when the RollbackTrans metho d
has finished running in async hro no us mo de.
pError is an o bjec t referenc e to an Error o bjec t if the value o f adStatus is set to
adStatusErrorsOccured.
adStatus is a Long value c o ntaining o ne o f the status values listed in Table 12-8 in
the BeginTransComplete event.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with
RollbackTrans metho d.
Event WillConnect (ConnectionString As String, UserID As String,
Password As String, Options As Long, adStatus As EventStatusEnum,
pConnection as Connection)
The WillConnect event is c alled befo re the pro c ess to establish that a c o nnec tio n
is started. Yo u c an o verride any o f the values in the ConnectionString, UserID,
Password, and Options pro perties. By default, the value o f adStatus is set to
adStatusOK. If yo u set adStatus to adStatusCancel, yo u will terminate the c o nnec tio n request. This will trigger the ConnectComplete event with an adStatus o f
adStatusErrorsOccurred.
ConnectionString is a String c o ntaining the same c o nnec tio n info rmatio n fo und
in the ConnectionString pro perty.
UserID c o ntains a String value with the UserID needed to ac c ess the database.
Chapter 12 ✦ Connecting to a database
Password c o ntains a String value with the passwo rd asso c iated with the spec ified
UserID.
Options o ptio nally passes o ne o f the values spec ified in Table 12-7 in the Open
metho d abo ve.
adStatus is a Long value c o ntaining o ne o f the status values listed in Table 12-8 in
the BeginTransComplete event.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
c o nnec tio n that triggered this event.
Event WillExecute (Source As String, CursorType As CursorTypeEnum,
LockType As LockTypeEnum, Options As Long, adStatus As EventStatus
Enum, pCommand As Command, pRecordset As Recordset, pConnection
as Connection)
The WillExecute event is c alled befo re a c o mmand is exec uted. Yo u c an o verride
any o f the values in the Source, CursorType, LockType and Options pro perties.
By default, the value o f adStatus is set to adStatusOK. If yo u set adStatus to
adStatusCancel, yo u will terminate the c o nnec tio n request. This will trigger the
ConnectComplete event with an adStatus o f adStatusErrorsOccurred.
Source is a String c o ntaining the SQL Statement, sto red pro c edure name, o r o ther
c o mmand to be exec uted.
CursorType c o ntains a CursorTypeEnum value desc ribing the type o f c urso r to be
used in the Recordset (see Table 12-9).
LockType c o ntains a LockTypeEnum value (see Table 12-10).
Options o ptio nally passes o ne o f the values spec ified in Table 12-7 in the Open
metho d abo ve.
adStatus is a Long value c o ntaining o ne o f the status values listed in Table 12-7 in
the BeginTransComplete event.
pCommand is an o bjec t referenc e to a Command o bjec t, if a Command o bjec t is abo ut
to be exec uted.
pRecordset is an o bjec t referenc e to a Recordset o bjec t, if a Recordset o bjec t
was the so urc e o f the func tio n to be exec uted.
pConnection is an o bjec t referenc e to the Connection o bjec t asso c iated with the
c o nnec tio n that triggered this event.
221
222
Part II ✦ Beginning Database Programming
Table 12-9
Values for CursorType
Constant
Value
Description
adOpenUnspecified
-1
The type of cursor isn’t specified.
adOpenForwardOnly
0
A forw ard-only cursor is used, w hich perm its
you only to scroll forw ard through the records
in the Recordset.
adOpenKeyset
1
A keyset cursor is used, w hich is sim ilar to a
dynam ic cursor, but doesn’t perm it you to see
records added by other users.
adOpenDynamic
2
A dynam ic cursor is used, w hich allow s you to
see records added by other users, plus any
changes and deletions m ade by other users.
adOpenStatic
3
A static cursor is used, w hich prevents you
from seeing any and all changes from other
users.
Table 12-10
Values for LockType
Constant
Value
Description
adLockUnspecified
-1
The type of locking isn’t specified.
adLockReadOnly
1
Doesn’t perm it you to change any values.
adLockPessimistic
2
Records are locked at the data source record
by record once the data in the record has
been changed.
adLockOptimistic
3
Records are locked only w hen you call the
UpdateMethod.
adLockBatchOptimistic
4
Records are not locked, and conflicts w ill be
returned for resolution after the
UpdateBatch m ethod has com pleted.
Chapter 12 ✦ Connecting to a database
The Error Object
The Error o bjec t c o ntains info rmatio n abo ut a spec ific erro r c o nditio n.
Error object properties
Table 12-11 lists the pro perties asso c iated with the Error o bjec t.
Table 12-11
Properties of the Error Object
Property
Description
Description
A String value containing a short text description of the error.
HelpContext
A Long value containing the help context ID reference w ithin the
help file specified by HelpFile. If no additional help can be
found, this value w ill contain a zero.
HelpFile
A String containing the nam e of the help file w here a m ore
detailed description of the error m ay be found. If no additional
help is available, this value w ill contain an em pty string.
NativeError
A Long containing a provider-specific error code.
Number
A Long containing the OLE DB error code num ber. This value is
unique to this specific error condition.
Source
A String containing the nam e of the object or application that
caused the error. ADO errors w ill generally have Source values of
the form at ADODB.objectname, ADOX.objectname, or ADOMD.
objectname, w here objectname is the nam e of the object that
caused the error.
SQLState
A String containing the standard five-character ANSI SQL
error code.
The Errors Collection
The Errors c o llec tio n c o ntains the set o f erro rs generated in respo nse to a spec ific
failure. If an o peratio n fails, the Errors c o llec tio n is c leared and all o f the individual
erro rs are rec o rded in the c o llec tio n.
223
224
Part II ✦ Beginning Database Programming
If yo u are using the Resync, UpdateBatch, o r CancelBatch metho ds o n a
Recordset o bjec t, yo u may generate a set o f warnings that will no t raise the On
Error c o nditio n in Visual Basic . Thus, it is impo rtant to c hec k fo r warnings when
using these metho ds and take the appro priate ac tio n.
Caution
I’m certain it didn’t error again: Successfully perform ing a function w ill not clear
the Errors collection. Thus, the inform ation from a previous error w ill rem ain in
the collection until it is either explicitly cleared or another error occurs. For this
reason, it is very im portant that you clear the Errors collection after you handle
the error condition and before you resum e norm al processing. Otherw ise, you
m ay falsely detect an error condition.
Errors collection properties
Table 12-12 lists the pro perties asso c iated with the Errors c o llec tio n.
Table 12-12
Properties of the Errors Collection
Property
Description
Count
A Long value containing the num ber of errors in the collection.
Item(index)
An object reference to an Error object containing inform ation about a
particular error. To locate an error, specify a value in the range of 0 to
Count –1.
Errors collection methods
The Errors c o llec tio n c o ntains metho ds to manage the c o llec tio n o f erro r
info rmatio n.
Sub Clear ( )
The Clear metho d initializes the Errors c o llec tio n to the empty state.
Sub Refresh ( )
The Refresh metho d gets a fresh c o py o f the erro r info rmatio n fro m the data
pro vider.
Chapter 12 ✦ Connecting to a database
Connecting To Database Server
In the previo us c hapters, I pro vided all o f the info rmatio n nec essary to c o nnec t to
either the ADO Data Co ntro l o r the Data Enviro nment Designer and they to o k c are
o f c o nnec ting to the database server. Ho wever, if yo u plan to use the ADO o bjec ts
direc tly, yo u need to deal with a few issues yo urself.
Connection strings
A co nne ctio n string c o ntains the info rmatio n nec essary to c o nnec t yo ur applic atio n
to a data so urc e. This value is sto red in the ConnectionString pro perty o f the
Connection o bjec t. It c o nsists o f a series o f keywo rd c lauses separated by semic o lo ns (;). Yo u c reate a keywo rd c lause by spec ifying a keywo rd, an equal sign (=),
and then the value o f the keywo rd. If the same keywo rd is spec ified mo re than o nc e,
o nly the last o c c urrenc e will be used, exc ept in the c ase o f the provider keywo rd,
in whic h the first o c c urrenc e will be used.
Note
Spaces are permitted: A keyw ord alw ays ends w ith an equal sign, so special
characters, such as a space or a period, are legal.
Co nsider the fo llo wing c o nnec tio n string:
provider=sqloledb;data source=Athena;initial catalog=VB6DB
It uses the sqloledb pro vider and then spec ifies Athena as the data so urc e and
VB6DB as the initial c atalo g. No te the spac es inside bo th the data so urc e and the initial c atalo g keywo rds are legal.
Tip
Connection strings the easy way: Building a connection string to a new database
system can be a real headache, m aking sure that you have all the needed keyw ords to m ake the connection. Try building a dum m y application using the ADO
Data Control. Then configure the ConnectionString property using the
Properties dialog box. This creates the connection string and puts it in the
ConnectionString property. Then all you need to do is copy the connection
string to your application.
Provider keyword
The Provider keywo rd spec ifies the name o f the OLE DB pro vider that will be
used to c o nnec t to the data so urc e. If this keywo rd is no t inc luded in the c o nnec tio n string, the OLD DB Provider for ODBC will be used. Table 12-13 lists so me
c o mmo n databases and their OLE DB pro viders.
225
226
Part II ✦ Beginning Database Programming
Table 12-13
Common OLE DB Providers
Database
Provider
OLE DB Provider for ODBC
MSDASQL.1
Jet 3.51 (Access 97)
Microsoft.Jet.OLEDB.3.51
Jet 4.0 (Access 2000)
Microsoft.Jet.OLEDB.4.0
Oracle
MSDAORA.1
SQL Server 7
SQLOLEDB
Common keywords
Nearly all data pro viders suppo rt the keywo rds listed in Table 12-14. In many c ases,
these keywo rds will be all yo u need to c o nnec t to the data so urc e.
Table 12-14
Common Keywords for SQLOLEDB
Keyword
Alias
Description
Data Source
Server
Specifies the location of the database server or the
nam e of the file containing the data, depending on
the specific provider.
Initial Catalog
Database
Specifies the nam e of the default database on the
database server.
Password
PWD
Specifies the passw ord associated w ith the User Id
keyw ord.
User Id
UID
Specifies the user nam e that w ill be used to connect
to the database server.
Keywords for SQLOLEDB
Ac c essing an SQL Server database is very straightfo rward. All yo u need to do is
inc lude the Data Source keywo rd and either spec ify the user name and passwo rd
o r set the Trusted_Connection keywo rd to yes. Ho wever, there are a number o f
o ther keywo rds that c an pro vide additio nal func tio ns. Table 12-15 lists the set o f
keywo rds that are spec ific to SQL Server.
Chapter 12 ✦ Connecting to a database
Table 12-15
Common Keywords for SQLOLEDB
Keyword
Description
Application Name
Contains the nam e of the application program .
Connect Timeout
Specifies the num ber of seconds in w hich the database
server m ust respond before the connection w ill tim eout.
Integrated Security
When set to SSPI, Window s NT Authentication w ill be
used.
Trusted_Connection
Contains yes if you are using Window s NT
Authentication.
Workstation ID
Contains nam e of the client m achine.
Keywords for M icrosoft.Jet.OLEDB.4.0
When ac c essing a Jet database, yo u need to remember that there isn’t really a
database server invo lved, like there is with mo st o ther database systems. The
database is a spec ially fo rmatted disk file, whic h yo u referenc e in the Data Source
keywo rd. The o ther keywo rds have the no rmal meaning, and the list o f spec ific keywo rds fo r the Mic ro so ft Jet pro vider is listed in Table 12-16.
Table 12-16
Common Keywords for SQLOLEDB
Keyword
Description
Jet OLEDB:System Database
Contains the fully qualified file nam e for the
w orkgroup inform ation file.
Jet OLEDB:Registry Path
Specifies the registry key that contains values for
the database engine.
Jet OLEDB:Database Password
Contains the database passw ord.
Opening a connection
Opening a database c o nnec tio n is merely a matter o f dec laring an o bjec t, c reating a
new instanc e o f it, and then o pening the c o nnec tio n. The key is using the pro per
c o nnec tio n string when yo u o pen the c o nnec tio n.
227
228
Part II ✦ Beginning Database Programming
Declaring a Connection object
The fo llo wing line o f c o de dec lares the variable db as a Connection o bjec t.
Dim db As ADODB.Connection
Yo u c an use any o f the metho ds o r pro perties asso c iated with the Connection
o bjec t, but no t any o f the events. This is perfec tly fine fo r mo st pro grams. The
events o nly pro vide status info rmatio n that c an be safely igno red by mo st pro grams.
Tip
Globally speaking: When creating applications w ith m ultiple form s, I often add a
m odule to the program to hold objects that I w ant to access, including things like
the Connection object, w hich can easily share am ong m ultiple form s.
So metimes, ho wever, yo u might want to trac k this status info rmatio n. This is a great
plac e to inc lude extra sec urity c hec ks, sinc e yo u have the o ppo rtunity to review vario us func tio ns befo re they are ac tually perfo rmed, and c anc el them. To inc lude events
with the Connection o bjec t, yo u need to use the WithEvents keywo rd in the Dim
statement as in the statement belo w:
Dim WithEvents db As ADODB.Connection
Note
Qualifying for clarity: I usually use the ADODB prefix for all ADO objects. This elim inates confusion w ith other objects (such as the DAO) that have the sam e nam e.
The WithEvents keywo rd impo ses so me restric tio ns o n ho w yo u c an dec lare yo ur
o bjec t. Yo u c an o nly use it in Form mo dules and Class mo dules. Yo u c an’t use it in
a regular .BAS mo dule. Yo u also c an’t use the New keywo rd. Yo u must instantiate
the o bjec t using a Set statement with the New keywo rd.
Tip
Faster objects: While you can use the New keyw ord in a Dim statem ent to create
an object the first tim e it’s used, it adds code to every statem ent to see if the
object exists and create it if necessary.
Coding the Connection object
One o f the things I like best abo ut using the ADO o bjec ts direc tly, rather than using
the Data Enviro nment Designer o r the ADO Data Co mmand, is that the database
isn’t o pened fo r me when the pro gram is started. This allo ws me the o ppo rtunity
to ask the user fo r their user name and passwo rd befo re I o pen the database.
The Co nnec t Demo pro gram sho wn in Figure 12-1 is a very simple pro gram that
demo nstrates ho w to c o nnec t to an SQL Server database. It c o nsists o f two c o mmand butto ns that are used to c o nnec t and disc o nnec t fro m the database, plus two
text bo xes that allo w the user to enter their user name and passwo rd.
Chapter 12 ✦ Connecting to a database
Figure 12-1: The Connect Dem o program
Clic king the butto n labeled Co nnec t will fire the Command1_Click event, as sho wn
in Listing 12-1. I begin the ro utine by using the On Error Resume Next statement,
whic h prevents a run-time erro r fro m killing the pro gram. Ho wever, I need to be
c areful to explic itly c hec k fo r erro r c o nditio ns, o r an undetec ted erro r c o uld c ause
havo c with my pro gram.
Listing 12-1: The Command1_Click event in Connect Demo
Private Sub Command1_Click()
Dim p As ADODB.Property
On Error Resume Next
Set db = New ADODB.Connection
db.ConnectionString = “provider=sqloledb;” & _
“data source=Athena;initial catalog=VB6DB”
db.Properties(“User Id”).Value = Text1.Text
db.Properties(“Password”).Value = Text2.Text
db.Open
Continued
229
230
Part II ✦ Beginning Database Programming
Listing 12-1 (continued)
If db.State = adStateOpen Then
Command1.Enabled = False
Command2.Enabled = True
Else
WriteError
End If
End Sub
Next, I c reate a new instanc e o f the Connection o bjec t using the Set statement.
Then I set the vario us pro perties in the Connection befo re I o pen the c o nnec tio n.
While I c an set the ConnectionString pro perty direc tly, I need to set the values
fo r User Id and Password thro ugh the Properties c o llec tio n. Fo r these values, I
simply use the name o f the pro perty as the index in the Properties c o llec tio n and
assign the values I want to the Value pro perty. Of c o urse, these pro perties are spec ific to the pro vider that is used, so yo u need to see whic h o f these c usto m pro perties yo u really need.
CrossReference
Check “The Param eter Object” and “The Param eters Collection” in Chapter 13 for
m ore details about these objects.
Opening the connection
Onc e the pro perties are set, I invo ke the Open metho d to c o nnec t to the database
server. Ano ther way to handle the c o nnec tio n wo uld be to spec ify all o f the info rmatio n as part o f the c all to the Open metho d, as sho wn belo w:
db.Open “provider=sqloledb;data source=Athena; “ & _
“initial catalog=VB6DB”, Text1.Text, Text2.Text
This has the advantage o f fewer lines o f text, whic h means fewer plac es where
so mething c an go wro ng.
After I’ve used the Open metho d, I need to kno w if it was suc c essful. Had I no t used
the On Error statement, I c o uld safely assume that the Open metho d was suc c essful,
bec ause the pro gram wo uld had go tten a run-time erro r and died. Here I c an do o ne
o f two things. First, I c an c hec k the Errors o bjec t to see if there was an erro r and
c hec k the erro r c o de fo r the appro priate ac tio n. Sec o nd, I c an c hec k the State pro perty to make sure that the o bjec t’s state is o pen. If the c o nnec tio n is o pen, I’ll disable
the butto n that c o nnec ts to the database and enable the butto n that c lo ses the c o nnec tio n. If it isn’t, I’ll display an erro r message to the user with the WriteError
ro utine.
Chapter 12 ✦ Connecting to a database
Closing a connection
Clo sing a Connection o bjec t is merely a matter o f using the Close metho d and
releasing the reso urc es asso c iated with the o bjec t, whic h yo u c an see in Listing
12-2. If I was able to c lo se the c o nnec tio n, I will disable the Disc o nnec t butto n and
reenable the Co nnec t butto n so the user c an try c o nnec ting to the database again.
If the Close metho d generated an erro r, I’ll display the erro r using the WriteError
ro utine.
Listing 12-2: The Command2_Click event in Connect Demo
Private Sub Command2_Click()
db.Close
If db.State = adStateClosed Then
Set db = Nothing
Command2.Enabled = False
Command1.Enabled = True
Else
WriteError
End If
End Sub
Analyzing Errors
The Connection o bjec t’s Errors c o llec tio n c o ntains the info rmatio n abo ut the
mo st rec ent erro r that o c c urred. When perfo rming database func tio ns, it is quite
po ssible that a single request may generate multiple erro rs. Usually, the first erro r
is the mo st signific ant erro r, and the rest o f the erro rs are sec o ndary effec ts o f the
main erro r.
Retrieving erro r info rmatio nThe WriteError subro utine in Listing 12-3 is designed
to update a StatusBar c o ntro l with the results o f the mo st rec ent erro r. I c hec k the
Count pro perty to see ho w many erro rs are in the c o llec tio n, and if there’s o nly
o ne, I display it in the status bar. If I have multiple erro rs, I’ll display the first erro r
in the status bar just like I displayed the single erro r, and then use a For Each lo o p
to display eac h o f the individual erro r messages.
231
232
Part II ✦ Beginning Database Programming
Listing 12-3: The WriteError subroutine in Connect Demo
Private Sub WriteError()
Dim e As ADODB.Error
If db.Errors.Count = 1 Then
StatusBar1.SimpleText = “Error: “ & db.Errors(0).Description
Elseif db.Errors.Count > 1 Then
StatusBar1.SimpleText = “Multiple errors:” & _
db.Errors(0).Description
For Each e In db.Errors
MsgBox e.Description
Next e
End If
db.Errors.Clear
End Sub
It is impo rtant to c lear the Errors c o llec tio n befo re yo u issue the next database
request. The Errors c o llec tio n is o nly c leared auto matic ally the next time an erro r
is enc o untered. If yo u do n’t c lear the c o llec tio n befo re yo u issue a database request,
and then c hec k it afterwards, yo u c an’t be c ertain that the erro rs in the Errors c o llec tio n were c aused by the mo st rec ent database request.
There are two plac es where yo u sho uld c lear the Errors c o llec tio n. The first is
immediately after handling an erro r c o nditio n, as I did in the WriteError ro utine.
This ensures that Error o bjec t is c lear after pro c essing an erro r c o nditio n. Ho wever,
sinc e it is po ssible that yo u may no t c hec k every plac e there c an be an erro r, yo u
sho uld also c lear the Errors c o llec tio n befo re any c all that might result in an erro r.
Watching connection activity
The events asso c iated with the Connect o bjec t pro vide a way to c atc h an ac tivity
befo re and after it exec utes. This will allo w yo u to grab info rmatio n and display it to
the user, o r to review the request and deny it.
Displaying status information
The db_ConnectComplete event sho wn in Listing 12-4 will be fired after the user
c o nnec ts to the database. I begin by c hec king the adStatus parameter to see if the
Chapter 12 ✦ Connecting to a database
c o nnec tio n c o mpleted witho ut an erro r. If it did, I let the user kno w that they’re
c o nnec ted to the database. Otherwise, I get the erro r message fro m the pError
o bjec t and display it in the status bar.
Listing 12-4: The db_ConnectComplete event in Connect Demo
Private Sub db_ConnectComplete(ByVal pError As ADODB.Error, _
adStatus As ADODB.EventStatusEnum, _
ByVal pConnection As ADODB.Connection)
If adStatus = adStatusOK Then
StatusBar1.SimpleText = “Connected.”
Else
StatusBar1.SimpleText = “Error: “ & pError.Description
End If
End Sub
Canceling a request
The Complete events in the Co nnec tio n o bjec t merely indic ate the c urrent status o f
a request. The Will events, o n the o ther hand, are the perfec t plac e to review a
request and c anc el it if desired. Listing 12-5 takes advantage o f the db_WillConnect
event to see if the user really wants to c o nnec t to the database server.
Listing 12-5: The db_WillConnect event in Connect Demo
Private Sub db_WillConnect(ConnectionString As String, _
UserID As String, Password As String, Options As Long, _
adStatus As ADODB.EventStatusEnum, _
ByVal pConnection As ADODB.Connection)
If MsgBox(“Do you really want to connect?”, vbYesNo, _
“Connect to remote database”) = vbYes Then
StatusBar1.SimpleText = “Will connect.”
Else
adStatus = adStatusCancel
End If
End Sub
233
234
Part II ✦ Beginning Database Programming
I begin this ro utine by displaying a message bo x that asks the user if they really
want to c o nnec t to the database server. If the user respo nds no , I’ll c anc el the
request by setting the adStatus parameter to adStatusCancel. This will trigger
an erro r c o nditio n, whic h is interc epted by bo th the WriteError ro utine and the
ConnectComplete event. If the user respo nds yes, the status bar is updated, and
the Open metho d will be allo wed to c o ntinue.
Tip
So it’s contrived: The exam ple here is som ew hat contrived; how ever, in a real
application, you m ay w ant to restrict connections based on the tim e of date, day of
w eek, or particular value of the user nam e.
Thoughts on the Connection Object
The Connection object m anages the path to your database server. In m ost cases, you’ll
open the connection w hen your program begins and close it w hen it ends. You w on’t
bother w ith any of the events and you m ay not even specify any of the connection properties other than the connection string. After all, the m ain reason you w ant to use the
Connection object is to connect to the database. The real w ork of your application w ill be
done w ith the other objects in the ADO library.
Summary
In this c hapter yo u learned the fo llo wing:
✦ Yo u c an use the Connection o bjec t to establish a link between the database
c lient pro gram and the database server.
✦ Yo u c an use c o nnec tio n strings to spec ify the parameters that are passed to
the OLE DB pro vider to establish the c o nnec tio n to the database server.
✦ Yo u c an use the Error o bjec t to determine why the mo st rec ent database
request failed.
✦ Yo u c an use the events in the Connection o bjec t to gather info rmatio n abo ut
the vario us database requests sent to the database server and c anc el them if
desired.
✦
✦
✦