• Tidak ada hasil yang ditemukan

Directory listing of http: uap.unnes.ac.id ebook biblebook Visual Basic 6 com & Library Books

N/A
N/A
Protected

Academic year: 2017

Membagikan "Directory listing of http: uap.unnes.ac.id ebook biblebook Visual Basic 6 com & Library Books"

Copied!
24
0
0

Teks penuh

(1)

Connecting to

a database

I

n this c hapter, I’m go ing to disc uss the ADO Connection o bjec t in depth. Also , sinc e the Errorsc o llec tio n and the Erroro bjec t are tightly c o upled with the Connectiono bjec t, I’m go ing to c o ver them also . Ac c ess to a data pro vider is man-aged using the ADO Connectiono bjec t. Thus, every pro gram that uses a database server must inc lude at least o ne

Connectiono bjec t. Unless yo u are using multiple data pro viders o r ac c essing multiple database servers, o ne Connectiono bjec t is suffic ient.

The Connection Object

The Connectiono 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 Recordseto bjec ts, o r yo u c an c reate an instanc e o f the Connectiono bjec t and share it amo ng multiple Commandand Recordseto bjec ts.

Connection object properties

Table 12-1 lists the pro perties asso c iated with the Connectiono bjec t.

1 2

1 2

In This Cha pter

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

Analyz ing erro rs

(2)

Table 12-1

Properties of the Connection Object

Property Description

Attributes A Longvalue containing the transaction attributes for a connection (see Table 12-2). Note that not all data providers support this property.

CommandTimeout A Longcontaining 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 Stringcontaining the inform ation necessary to connect to a data source.

ConnectionTimeout A Longcontaining 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 Longcontaining the default location of the cursor service (see Table 12-3). This value w ill autom atically be inherited by the Recordsetobject using this Connectionobject.

DefaultDatabase A Stringcontaining the nam e of the default database.

Errors An object reference to an Errorscollection.

IsolationLevel A Longcontaining the level of transaction isolation (see Table 12-4).

Mode A Longcontaining the available perm issions for m odifying data (see Table 12-5).

Properties An object reference to a Propertiescollection containing provider-specific inform ation.

Provider A Stringcontaining the nam e of the data provider. This value m ay also be set as part of the ConnectionString.

State A Longdescribing the current state of the Commandobject. Multiple values can be com bined to describe the current state (see Table 12-6).

Version A Stringcontaining the current ADO version num ber.

See Chapter 22, “Integrating XM L 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.

(3)

Table 12-2

Values for Attributes

Constant Value Description

adXactCommitRetaining 131072 Calling CommitTransautom atically starts a new transaction.

adXactAbortRetaining 262144 Calling RollbackTransautom 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 Requerythe Recordset

object.

(4)

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

adModeShareDenyNoneto propagate sharing restrictions to all sub-records of the current Record.

Connection object methods

(5)

Table 12-6

Values for State

Constant Value Description

adStateClosed 0 TheCommandobject is closed.

adStateOpen 1 The Commandobject is open.

adStateConnecting 2 The Commandobject is connecting to the database.

adStateExecuting 4 The Commandobject is executing.

adStateFetching 8 Row s are being retrieved.

Function BeginTrans ( ) As Long

The BeginTransmetho 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 CommitTranso r RollbackTrans,will return two .

Sub Cancel ( )

The Cancelmetho d is used to terminate an async hro no us task started by the Executeo r Openmetho ds.

Sub Close ( )

The Closemetho d c lo ses the c o nnec tio n to the data pro vider. It will also c lo se any o pen Recordseto bjec ts and set the ActiveConnectionpro perty o f any Command o bjec ts to Nothing.

Sub CommitTrans ( )

The CommitTransmetho d ends a transac tio n and saves the c hanges to the datab ase. Depending o n the Attributespro perty, a new transac tio n may auto -matic ally b e started.

Function Execute (CommandText As String, [RecordsAffected],

[Options As Long = -1]) As Recordset

(6)

CommandTextis a Stringc 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.

RecordsAffectedo ptio nally returns a Longvalue with the number o f rec o rds affec ted by the c o mmand.

Optionso 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 Commando bjec t.

Sub Open ([ConnectionString As String], [UserID As String],

[Password As String], [Options As Long = -1])

The Openmetho d initializes the Connectiono bjec t by establishing a c o nnec tio n to a data pro vider.

ConnectionStringis a Stringvalue c o ntaining the same c o nnec tio n info rmatio n fo und in the ConnectionStringpro perty. The value in this parameter will o verride the value in the pro perty.

UserIDc o ntains a Stringvalue 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.

Passwordc o ntains a Stringvalue 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

ConnectionStringparameter o r pro perty.

Optionso ptio nally passes o ne o f the values spec ified in Table 12-7. If yo u spec ify adAsyncConnect, the ConnectCompleteevent 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.

(7)

Function OpenSchema (Schema As SchemaEnum,

[Restrictions], [SchemaID]) As Recordset

The OpenSchemametho d returns database info rmatio n fro m the data pro vider. A Recordseto 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.

Schemais an enumerated value spec ifying the type o f info rmatio n to be returned.

Restrictionsc o ntains an array o f query c o nstraints.

SchemaIDo 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 Schemaparameter is set to adSchemaProviderSpecific.

So you want to write a database utility: The OpenSchemam 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 docu-m entation for detailed infor-m ation about this m ethod.

Sub RollbackTrans ( )

The RollbackTransmetho d ends a transac tio n and disc ards any c hanges to the datab ase. Depending o n the Attributespro perty, a new transac tio n may auto -matic ally b e started.

Connection object events

The Connectiono bjec t c o ntains events that allo w yo u to interc ept status info rma-tio n and determine erro r c o ndirma-tio ns while yo u have a c o nnec rma-tio n to yo ur data so urc e.

Event BeginTransComplete (TransactionLevel As Long, pError As Error,

adStatus As EventStatusEnum, pConnection As Connection)

The BeginTransCompleteis c alled after the BeginTransmetho d has finished running in async hro no us mo de.

TransactionLevelis a Longvalue c o ntaining the new transac tio n level.

pErroris an o bjec t referenc e to an Erroro bjec t if the value o f adStatusis set to adStatusErrorsOccured.

adStatusis a Longvalue that c o ntains o ne o f the status values listed in Table 12-8.

pConnectionis an o bjec t referenc e to the Connectiono bjec t asso c iated with the BeginTransmetho d.

(8)

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 CommitTransCompleteis c alled when the CommitTransmetho d has finished running in async hro no us mo de.

pErroris an o bjec t referenc e to an Erroro bjec t if the value o f adStatusis set to adStatusErrorsOccured.

adStatusis a Longvalue that c o ntains o ne o f the status values listed in Table 12-8 in the BeginTransCompleteevent.

pConnectionis an o bjec t referenc e to the Connectiono bjec t asso c iated with the CommitTransmetho d.

Event ConnectComplete (pError As Error, adStatus As

EventStatusEnum, pConnection As Connection)

The ConnectCompleteis c alled when the Connectmetho d has finished running in async hro no us mo de.

(9)

adStatusis a Longvalue that c o ntains o ne o f the status values listed in Table 12-8 in the BeginTransCompleteevent.

pConnectionis an o bjec t referenc e to the Connectiono bjec t asso c iated with the Connectmetho d.

Event Disconnect (adStatus As EventStatusEnum, pConnection

As Connection)

The Disconnectevent is c alled when the c o nnec tio n has been dro pped fro m the data so urc e.

adStatusis a Longvalue that always c o ntains adStatusOK.

pConnectionis an o bjec t referenc e to the Connectiono bjec t asso c iated with the CommitTransmetho d.

Event ExecuteComplete (RecordsAffected As Long, pError As Error,

adStatus As EventStatusEnum, pCommand As Command, pRecordset As

Recordset, pConnection as Connection)

The ExecuteCompleteevent is c alled when the Executemetho d has finished run-ning in async hro no us mo de.

RecordsAffectedis a Longvalue c o ntaining the number o f rec o rds affec ted by the c o mmand exec uted by the Executemetho d.

pErroris an o bjec t referenc e to an Erroro bjec t if the value o f adStatusis set to adStatusErrorsOccured.

adStatusis a Longvalue c o ntaining o ne o f the status values listed in Table 12-8 in the BeginTransCompleteevent.

pCommandis an o bjec t referenc e to a Commando bjec t, if a Commando bjec t was exe-c uted.

pRecordsetis an o bjec t referenc e to a Recordseto bjec t c o ntaining the results o f the c o mmand’s exec utio n.

(10)

Event InfoM essage (pError As Error, adStatus As EventStatusEnum,

pConnection as Connection)

The InfoMessageevent is c alled when a warning message is rec eived by the c ur-rent c o nnec tio n.

pErroris an o bjec t referenc e to an Erroro bjec t if the value o f adStatusis set to adStatusErrorsOccured.

adStatusis a Longvalue c o ntaining o ne o f the status values listed in Table 12-8 in the BeginTransCompleteevent.

pConnectionis an o bjec t referenc e to the Connectiono bjec t asso c iated with the message.

Event RollbackTransComplete (pError As Error, adStatus As

EventStatusEnum, pConnection as Connection)

The RollbackTransCompleteevent is c alled when the RollbackTransmetho d has finished running in async hro no us mo de.

pErroris an o bjec t referenc e to an Erroro bjec t if the value o f adStatusis set to adStatusErrorsOccured.

adStatusis a Longvalue c o ntaining o ne o f the status values listed in Table 12-8 in the BeginTransCompleteevent.

pConnectionis an o bjec t referenc e to the Connectiono bjec t asso c iated with RollbackTransmetho d.

Event WillConnect (ConnectionString As String, UserID As String,

Password As String, Options As Long, adStatus As EventStatusEnum,

pConnection as Connection)

The WillConnectevent 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 Optionspro perties. By default, the value o f adStatusis set to adStatusOK. If yo u set adStatusto adStatusCancel, yo u will terminate the c o n-nec tio n request. This will trigger the ConnectCompleteevent with an adStatuso f adStatusErrorsOccurred.

ConnectionStringis a Stringc o ntaining the same c o nnec tio n info rmatio n fo und in the ConnectionStringpro perty.

(11)

Passwordc o ntains a Stringvalue with the passwo rd asso c iated with the spec ified UserID.

Optionso ptio nally passes o ne o f the values spec ified in Table 12-7 in the Open metho d abo ve.

adStatusis a Longvalue c o ntaining o ne o f the status values listed in Table 12-8 in the BeginTransCompleteevent.

pConnectionis an o bjec t referenc e to the Connectiono 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 WillExecuteevent 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, LockTypeand Optionspro perties. By default, the value o f adStatusis set to adStatusOK. If yo u set adStatusto adStatusCancel, yo u will terminate the c o nnec tio n request. This will trigger the ConnectCompleteevent with an adStatuso f adStatusErrorsOccurred.

Sourceis a Stringc o ntaining the SQL Statement, sto red pro c edure name, o r o ther c o mmand to be exec uted.

CursorTypec o ntains a CursorTypeEnumvalue desc ribing the type o f c urso r to be used in the Recordset( see Table 12-9) .

LockTypec o ntains a LockTypeEnumvalue ( see Table 12-10) .

Optionso ptio nally passes o ne o f the values spec ified in Table 12-7 in the Open metho d abo ve.

adStatusis a Longvalue c o ntaining o ne o f the status values listed in Table 12-7 in the BeginTransCompleteevent.

pCommandis an o bjec t referenc e to a Commando bjec t, if a Commando bjec t is abo ut to be exec uted.

pRecordsetis an o bjec t referenc e to a Recordseto bjec t, if a Recordseto bjec t was the so urc e o f the func tio n to be exec uted.

(12)

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

(13)

The Error Object

The Erroro 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 Erroro bjec t.

Table 12-11

Properties of the Error Object

Property Description

Description A Stringvalue containing a short text description of the error.

HelpContext A Longvalue 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 Stringcontaining 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 Longcontaining a provider-specific error code.

Number A Longcontaining the OLE DB error code num ber. This value is unique to this specific error condition.

Source A Stringcontaining the nam e of the object or application that caused the error. ADO errors w ill generally have Sourcevalues of the form at ADODB.objectname, ADOX.objectname,or ADOMD.

objectname, w here objectnameis the nam e of the object that caused the error.

SQLState A Stringcontaining the standard five-character ANSI SQL error code.

The Errors Collection

(14)

If yo u are using the Resync, UpdateBatch, o r CancelBatchmetho ds o n a Recordseto bjec t, yo u may generate a set o f warnings that will no t raise the On Errorc 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.

I’m certain it didn’t error again:Successfully perform ing a function w ill not clear the Errorscollection. 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 Errorscollection 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 Errorsc o llec tio n.

Table 12-12

Properties of the Errors Collection

Property Description

Count A Longvalue containing the num ber of errors in the collection.

Item(index) An object reference to an Errorobject 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 Errorsc 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 Clearmetho d initializes the Errorsc o llec tio n to the empty state.

Sub Refresh ( )

The Refreshmetho d gets a fresh c o py o f the erro r info rmatio n fro m the data pro vider.

(15)

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 stringc 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 ConnectionStringpro perty o f the Connectiono bjec t. It c o nsists o f a series o f keywo rd c lauses separated by semi-c o lo ns ( ;) . Yo u semi-c reate a keywo rd semi-c lause by spesemi-c 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 providerkeywo rd, in whic h the first o c c urrenc e will be used.

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 sqloledbpro vider and then spec ifies Athenaas the data so urceand VB6DBas the initial c atalo g. No te the spac es inside bo th the data so urc e and the ini-tial c atalo g keywo rds are legal.

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

ConnectionStringproperty. Then all you need to do is copy the connection string to your application.

Provider keyword

The Providerkeywo rd spec ifies the name o f the OLE DB pro vider that will b e 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 ODBCwill b e used. Tab le 12-13 lists so me c o mmo n datab ases and their OLE DB pro viders.

(16)

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

(17)

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 yesif 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 key-wo 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

(18)

Declaring a Connection object

The fo llo wing line o f c o de dec lares the variable db as a Connectiono 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.

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 Connectionobject, 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 vari-o us func tivari-o ns befvari-o re they are ac tually perfvari-o rmed, and c anc el them. Tvari-o inc lude events with the Connectiono bjec t, yo u need to use the WithEventskeywo rd in the Dim statement as in the statement belo w:

Dim WithEvents db As ADODB.Connection

Qualifying for clarity: I usually use the ADODBprefix for all ADO objects. This elim -inates confusion w ith other objects (such as the DAO) that have the sam e nam e.

The WithEventskeywo 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 Formmo dules and Classmo dules. Yo u c an’t use it in a regular .BASmo dule. Yo u also c an’t use the Newkeywo rd. Yo u must instantiate the o bjec t using a Setstatement with the Newkeywo rd.

Faster objects: While you can use the Newkeyw ord in a Dimstatem 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 b est ab o ut using the ADO o b jec ts direc tly, rather than using the Data Enviro nment Designer o r the ADO Data Co mmand, is that the datab ase 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 b efo re I o pen the datab ase.

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 m-mand 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.

(19)

Figure 12-1: The Connect Dem o program

Clic king the butto n labeled Co nnec t will fire the Command1_Clickevent, as sho wn in Listing 12-1. I begin the ro utine by using the On Error Resume Nextstatement, 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

(20)

Listing 12-1

(continued)

Next, I c reate a new instanc e o f the Connectiono bjec t using the Setstatement. Then I set the vario us pro perties in the Connectionbefo re I o pen the c o nnec tio n. While I c an set the ConnectionStringpro perty direc tly, I need to set the values fo r User Idand Passwordthro ugh the Propertiesc o llec tio n. Fo r these values, I simply use the name o f the pro perty as the index in the Propertiesc o llec tio n and assign the values I want to the Valuepro perty. Of c o urse, these pro perties are spe-c ifispe-c to the pro vider that is used, so yo u need to see whispe-c h o f these spe-c usto m pro per-ties yo u really need.

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 Openmetho 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 r-matio n as part o f the c all to the Openmetho 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 Openmetho d, I need to kno w if it was suc c essful. Had I no t used the On Errorstatement, I c o uld safely assume that the Openmetho 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 Errorso 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 Statepro p-erty 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 n-nec tio n. If it isn’t, I’ll display an erro r message to the user with the WriteError ro utine.

(21)

Closing a connection

Clo sing a Connectiono bjec t is merely a matter o f using the Closemetho 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 Closemetho 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 Connectiono bjec t’s Errorsc 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.

(22)

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 Errorsc o llec tio n befo re yo u issue the next database request. The Errorsc 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 Errorsc o l-lec 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 Errorsc o llec tio n. The first is immediately after handling an erro r c o nditio n, as I did in the WriteErrorro utine. This ensures that Erroro 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 Errorsc 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 Connecto 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

(23)

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 Completeevents in the Co nnec tio n o bjec t merely indic ate the c urrent status o f a request. The Willevents, 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

(24)

I b egin this ro utine b y displaying a message b o x that asks the user if they really want to c o nnec t to the datab ase server. If the user respo nds no , I’ll c anc el the req uest b y setting the adStatusparameter to adStatusCancel. This will trigger an erro r c o nditio n, whic h is interc epted b y b o th the WriteErrorro utine and the ConnectCompleteevent. If the user respo nds yes, the status b ar is updated, and the Openmetho d will b e allo wed to c o ntinue.

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.

Tip

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 proper-ties other than the connection string. After all, the m ain reason you w ant to use the

Connectionobject 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 Connectiono 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 Erroro bjec t to determine why the mo st rec ent database

request failed.

✦Yo u c an use the events in the Connectiono 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.

Gambar

Table 12-1Properties of the Connection Object
Table 12-2Values for Attributes
Table 12-5Values for Mode
Table 12-8Values for adStatus
+7

Referensi

Dokumen terkait

Adapun tujuan diadakannya indeks saham syariah sebagaiman Jakarta Islamic Index yang melibatkan 30 saham terpilih, yaitu sebagai tolak ukur untuk mengukur kinerja

You can download and install the soft file of this incredible book Time Mends (Timber Wolves, Book 2) By Tammy Blackwell currently and in the link offered.. Yeah, different with

Indonesia merupakan negara dengan orang muslim terbesar didunia, akan tetapi setiap ormas muslim sendiri tentunya berbeda dalam memutuskan suatu masalah baru yang muncul

54 Tahun 2010 tentang Pengadaan Barang/Jasa Pemerintah serta menindaklanjuti proses seleksi untuk Paket Pekerjaan Pengadaan Meubelair (985 Unit) , bersama ini kami

Additionally, Aaron developed a wide variety of exercises and stretches specific for posture and alignment based on the personal needs and desires of the many clients he has served

n salinannya sebagaimana tertuang dalam lam proses pembuktian kualifikasi

Uang merupakan uang milik masyarakat atau uang beredar di masyarakat (di luar Bank Sentral seperti Bank Indonesia dan perbankan atau semua bank), yang terdiri dari :.. Uang Kertas

As everybody recognizes, book Carr: Five Years Of Rape And Murder By Edna Buchanan is very popular as the window to open up the globe. It implies that reading publication Carr: