• 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!
30
0
0

Teks penuh

(1)

Using

ify a c o mmand that will retrieve data fro m yo ur database. Typic ally this o bjec t is used with sto red pro c edures and SQL queries that inc lude a series o f parameters.

Introducing the ADO

Command Object

After yo u have an o pen c o nnec tio n, the first thing yo u’re go ing to want to do is to exec ute so me c o mmands. Co mmands are defined in the Commando bjec t and c an be SQL statements o r c alls to sto red pro c edures. So me c o mmands, partic ularly tho se that use sto red pro c edures, may have parameters that supply additio nal info rmatio n to the c o mmand o r return info rmatio n after the c o mmand was exec uted. Parameter info rmatio n is sto red in the Parametersc o llec tio n, with eac h parameter hav-ing its o wn Parametero bjec t. Also , depending o n the partic u-lar c o mmand, it may o r may no t return a Recordseto bjec t c o ntaining ro ws o f info rmatio n fro m yo ur database.

Discussing Commandobjects w ithout talking about Recordset

objects can be difficult, since the prim ary reason for using

Commandobjects is to create Recordsets. See Chapter 14 for m ore inform ation about Recordsetobjects.

(2)

Cross-The Command Object

The Commando bjec t c o ntains info rmatio n abo ut an SQL statement o r sto red pro c e-dure yo u wish to exec ute against a database. Yo u may o ptio nally inc lude a list o f parameters that will be passed to the sto red pro c edure. If the c o mmand returns a set o f ro ws, the Commando bjec t will return a Recordseto bjec t c o ntaining the results.

Command object properties

Table 13-1 lists the pro perties asso c iated with the Commando bjec t.

Table 13-1

Properties of the Command Object

Property Description

ActiveConnection A Variantarray containing an object reference to the

Connectionobject used to access the database. May also contain a valid connection string that w ill dynam ically create a connection to your database w hen you use the Execute

m ethod.

CommandText A Stringvalue containing an SQL statem ent, a stored procedure nam e, or other provider com m and to be executed.

CommandTimeout A Longvalue 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.

CommandType An enum erated type (see Table 13-2) describing the type of com m and to be executed.

Name A Stringcontaining the nam e of the object.

Parameters An object reference to a Parameterscollection containing the param eters that w ill be passed to a stored procedure or a param eterized query.

Prepared A Boolean, w hen TRUE, m eans that the com m and should be prepared before execution.

Properties An object reference to a Propertiescollection containing additional inform ation about the Commandobject.

(3)

Table 13-2

Values for CommandType

Constant Value Description

adCmdUnspecified -1 CommandTypeshould be autom atically determ ined.

adCmdText 1 CommandTextcontains either an SQL statem ent or stored procedure call.

adCmdTable 2 CommandTextcontains the nam e of a table in the database.

adCmdStoredProcedure 4 CommandTextcontains the nam e of a stored procedure.

adCmdUnknown 8 The type of com m and isn’t know n.

adExecuteNoRecords 128 Indicates that the com m and w ill not return any row s or w ill autom atically discard any row s that are generated. Must be used w ith adCmdText

or adCmdStoredProcedure.

adCmdFile 256 CommandTextis the nam e of a persistently stored Recordset.

adCmdTableDirect 512 CommandTextcontains the nam e of a database table.

Table 13-3

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.

(4)

Command bject methods

The Commando bjec t c o ntains o nly three metho ds: Cancel, CreateParameter, and Execute.

Sub Cancel( )

The Cancelmetho d is used to terminate an async hro no us task started by the Executemetho d.

Function CreateParameter ([Name As String], [Type As DataTypeEnum =

adEmpty], [Direction As ParameterDirectionEnum = adParamInput],

[Size As Long], [Value]) As Parameter

The CreateParametermetho d c reates a new Parametero bjec t, whic h may be added to the Parametersc o llec tio n using the Parameters.Appendmetho d.

Namespec ifies the name o f the parameter.

Typespec ifies the data type o f the parameter.

Directionspec ifies whether the parameter is input o nly, o utput o nly, o r bo th input and o utput.

Sizespec ifies the length o f the parameter. This parameter is o nly impo rtant when yo u have a variable length data type, suc h as a string o r an array.

Valuespec ifies the value o f the parameter.

Function Execute ([RecordsAffected], [Parameters],

[Options As Long = -1]) As Recordset

The Executemetho d runs the SQL statement o r sto red pro c edure spec ified in the Commando bjec t. 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.

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

(5)

Optionso ptio nally passes a c o mbinatio n o f the values spec ified in Table 13-4. No te that so me o f these values are the same as tho se available fo r the CommandType pro perty.

Table 13-4

Values for Options

Constant Value Description

adOptionUnspecified -1 No options are specified.

adCmdText 1 CommandTextcontains either an SQL statem ent or stored procedure call.

adCmdTable 2 CommandTextcontains the nam e of a table in the database.

adCmdStoredProcedure 4 CommandTextcontains the nam e of a stored procedure.

adCmdUnknown 8 The type of com m and isn’t know n.

adAsyncExecute 16 The com m and should be executed asynchronously.

adAsyncFetch 32 After the num ber of row s specified in the

CacheSizeproperty of the Recordset

object are returned, the rem aining row s w ill be returned asynchronously.

adAsyncFetchNonBlocking 64 The m ain thread isn’t blocked w hile retrieving row s. If the current row hasn’t been retrieved, the current row w ill be m oved to the end of the file.

adExecuteNoRecords 128 Indicates that the com m and w ill not return any row s or w ill autom atically discard any row s that are generated. Must be used w ith either the adCmdTextor

adCmdStoredProcedurevalues.

adCmdFile 256 CommandTextis the nam e of a persistently stored Recordset.

(6)

The Parameter Object

The Parametero bjec t c o ntains info rmatio n abo ut a parameter used in a sto red pro c edure o r parameterized query defined in a Commando bjec t.

Parameter object properties

Table 13-6 lists the pro perties asso c iated with the Parametero bjec t.

Table 13-6

Properties of the Parameter Object

Property Description

Attributes An enum erated type describing the characteristics of the param eter (see Table 13-7).

Direction An enum erated type that describes w hether the param eter is an input-only, input/ outpu, or output-only param eter (see Table 13-8).

Name A Stringvalue containing the nam e of the param eter.

NumericScale A Bytevalue containing the num ber of digits to the right of the decim al point for a num eric field.

Precision A Bytevalue containing the total num ber of digits in a num eric field.

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

Type An enum erated type (see Table 13-9) containing the OLE DB data type of the field.

Value A Variantarray containing the current value of the param eter.

Table 13-7

Values for Attributes

Constant Value Description

adFldUnspecified -1 The provider doesn’t supply field attributes.

(7)

Constant Value Description

adFldUpdateable 4 The field’s value m ay be changed.

adFldUnknownUpdateable 8 The provider can’t determ ine if you can change the field’s value.

adFldFixed 16 The field contains fixed-length data.

adFldIsNullable 32 The field w ill accept Nullvalues.

adFldMayBeNull 64 The field m ay contain a Nullvalue.

adFldLong 128 The field contains a long binary value and you should use the AppendChunkand

GetChunkm ethods to access its data.

adFldRowID 256 The field contains an identity value that can’t be changed.

adFldRowVersion 512 The field contains a tim e stam p value that is used to track updates.

adFldCacheDeferred 4096 This field is cached by the provider and subsequent reads and w rites are done from cache.

adFldIsChapter 8192 The field contains a chapter value, w hich specifies a specific child Recordsetrelated to this parent field.

adFldNegativeScale 16384 The field contains a num eric colum n that supports negative scale values.

adFldKeyColumn 32768 The field is (or is at least part of) the prim ary key for the table.

adFldIsRowURL 65536 The field contains the URL that nam es the resource from the data store represented by the record.

adFldIsDefaultStream 131072 The field contains the default stream for the resource represented by the record.

(8)

Table 13-8

Values for Direction

Constant Value Description

adParamUnknown 0 The direction of the param eter is unknow n.

adParamInput 1 The param eter is an input-only param eter.

adParamOutput 2 The param eter is an output-only param eter.

adParamInputOutput 3 The param eter is both an input and an output param eter.

adParamReturnValue 4 The param eter contains a return value.

Table 13-9

Values for Type

Constant Value Description

adEmpty 0 This field has no value (DBTYPE_EMPTY).

adSmallInt 2 This field has an Integervalue (DBTYPE_I2).

adInteger 3 This field has a Longvalue (DBTYPE_I4).

adSingle 4 This field has a Singlevalue (DBTYPE_R4).

adDouble 5 This field has a Doublevalue (DBTYPE_R8).

adCurrency 6 This field has a Currencyvalue (DBTYPE_CY).

adDate 7 This field has a Datevalue (DBTYPE_DATE).

adBSTR 8 This field has a null-term inated Unicode string (DBTYPE_BSTR).

adIDispatch 9 This field has a pointer to an IDispatch

interface in a COM object (DBTYPE_IDISPATCH).

adError 10 This field has a 32-bit error code (DBTYPE_ERROR).

(9)

Constant Value Description

adVariant 12 This field has a Variantvalue

(DBTYPE_VARIANT). Note that this type is not supported by ADO and causes unpredictable results.

adIUknown 13 This field has a pointer to an IUnknown

interface in a COM object (DBTYPE_ IUNKNOWN).

adDecimal 14 This field has an exact num eric value w ith a fixed precision and scale (DBTYPE_ DECIMAL).

adTinyInt 16 This field has a one byte signed integer (DBTYPE_I1).

adUnsignedTinyInt 17 This field has a one byte unsigned integer (DBTYPE_UI1).

adUnsignedInt 18 This field has a tw o byte unsigned integer (DBTYPE_UI2).

adUnsignedInt 19 This field has a four byte unsigned integer (DBTYPE_UI4).

adBigInt 20 This field has an 8-byte signed integer (DBTYPE_I8).

adUnsignedBigInt 21 This field has an 8-byte unsigned integer (DBTYPE_UI8).

adFileTime 64 This field has a 64-bit date-tim e value represented as the num ber of 100-nanosecond intervals since 1 January 1601 (DBTYPE_FILETIME).

adGUID 72 This field has a globally unique identifier value (DBTYPE_GUID).

adBinary 128 This field has a Binaryvalue (DBTYPE_ BYTES).

adChar 129 This field has a Stringvalue (DBTYPE_ STR).

adWChar 130 This field contains a null-term inated Unicode character string (DBTYPE_WSTR).

adNumeric 131 This field contains an exact num eric value w ith a fixed precision and scale (DBTYPE_ NUMERIC).

(10)

Table 13-9

(continued)

Constant Value Description

adUserDefined 132 This field contains a user-defined value (DBTYPE_UDT).

adDBDate 133 This field has a date value using the

YYYYMMDDform at (DBTYPE_DBDATE).

adDBTime 134 This field has a tim e value using the

HHMMSSform at (DBTYPE_DBTIME).

adDBTimeStamp 135 This field has a date-tim e stam p in the

YYYYMMDDHHMMSSform at (DBTYPE_DBTIMESTAMP).

adChapter 136 This field has a 4-byte chapter value that identifies the row s in a child row set (DBTYPE_HCHAPTER).

adPropVariant 138 This field has an Autom ation PROPVARIANT

(DBTYPE_PROP_VARIANT).

adVarNumeric 139 This field contains a num eric value. (Available for Parameterobjects only.)

adVarChar 200 This field has a String. (Available for

Parameterobjects only.)

adLongVarChar 201 This field has a long character value. (Available for Parameterobjects only.)

adVarWChar 202 This field has a null-term inated Unicode character string value. (Available for

Parameterobjects only.)

adLongVarWChar 203 This field has a long null-term inated character string value. (Available for

Parameterobjects only.)

adVarBinary 204 This field has a binary value. (Available for

Parameterobjects only.)

(11)

Parameter object methods

There is o nly o ne metho d available fo r the Parametero bjec t: the AppendChunk metho d.

Sub AppendChunk (Data As Variant)

The AppendChunkmetho d is used to add data to a large text o r b inary field. The first time the AppendChunkmetho d is used, the value in Datawill o verwrite any existing data in the field. Fo r sub seq uent c alls, simply append data to the end o f the existing data. Datais a Variantarray c o ntaining the data to b e appended to the end o f the field.

The Parameters Collection

The Parametersc o llec tio n c o ntains the set o f parameters asso c iated with a Commando bjec t.

Parameters collection properties

Table 13-10 lists the pro perties asso c iated with the Parametersc o llec tio n.

Table 13-10

Properties of the Parameters Collection

Property Description

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

Item(index) An object reference to a Parameterobject containing inform ation about a particular field in the Recordset. To locate a field, specify a value in the range of 0 to Count–1 or the nam e of the

Parameter.

Parameters collection methods

(12)

Sub Append (Object As Object)

The Appendmetho d adds a Parametero bjec t to the c o llec tio n. The Typepro perty o f the Parametero bjec t must be defined befo re yo u c an add it to the c o llec tio n. Objectis a Parametero bjec t c o ntaining the new parameter.

Use the CreateParameterm ethod of the Commandobject to create a new

Parameterobject, then use the Appendm ethod to add it to the collection.

Sub Delete (Index As Variant)

The Deletemetho d remo ves an o bjec t spec ified by Indexfro m the c o llec tio n. Indexis either a Stringvalue c o ntaining the name o f the parameter o r a Long value c o ntaining the o rdinal po sitio n o f the Parametero bjec t to be deleted.

Sub Refresh( )

The Refreshmetho d c an b e used to retrieve info rmatio n ab o ut the parameters in a sto red pro c edure fro m the data pro vider. To use Refreshin this fashio n, yo u need a valid Commando b jec t with an ac tive c o nnec tio n to the data so urc e. Then all yo u need to do is spec ify values fo r CommandTextand CommandTypeand use the Parameters.Refreshmetho d. This will retrieve all o f the info rmatio n fo r the sto red pro c edure fro m the data pro vider. No te that this wo rks o nly if yo ur data pro vider suppo rts sto red pro c edures o r an SQL q uery with emb edded parameters ( also kno wn as a parame te riz e d que ry) .

Running SQL Statements

A Commando bjec t c o ntains all o f the info rmatio n nec essary to send a c o mmand to the database server fo r exec utio n. So metimes the c o mmand will need parameters, while at o ther times it will no t. Depending o n the c o mmand yo u want to exec ute, it may return no thing o r a Recordseto bjec t c o ntaining the set o f ro ws selec ted fro m the database. No matter what the c o mmand is, the appro ac h yo u use to define it and run it is basic ally the same.

Running a simple command

Every Commandyo u exec ute needs at least two piec es o f info rmatio n befo re yo u c an use it. Yo u must set the CommandTextto the c o mmand yo u want to exec ute and yo u must set the ActiveConnectionpro perty to an o pen Connectiono bjec t.

(13)

SQL statement, a sto red pro c edure, o r a table name befo re it c an exec ute it. While this extra o verhead isn’t large by itself, it c an be signific ant when yo u multiply it by the number o f requests the server must exec ute.

The Co mmand Demo pro gram ( see Figure 13-1) is based o n the Co nnec tio n Demo pro gram fro m Chapter 12. All o f the c o de and fo rm elements are c arried o ver intac t, altho ugh I added a few new c o mmand butto ns and Clickevents to demo nstrate ho w to use the Commando bjec t.

Figure 13-1: Running the Com m and Dem o program

The Com m and Dem o program can be found on the CD-ROM in the \ VB6DB\ Chapter13\ Com m andDem o directory.

.

Listing 13-1 sho ws ho w yo u c an use a Commando bjec t to c reate a database table. In this example, I c reate a table c alled MyTable. Ho wever, this tec hnique c an be used to exec ute any SQL statement exc ept fo r the Se le ctstatement. ( The Se le ct state-ment will return a Recordseto bjec t, whic h requires so me additio nal c o de.)

Listing 13-1:

The Command5_Click event in Command Demo

Private Sub Command5_Click() Dim c As ADODB.Command On Error Resume Next

Continued On the

(14)

Listing 13-1

(continued)

Set c = New ADODB.Command Set c.ActiveConnection = db

c.CommandText = “Create Table MyTable (MyColumn Char (10))” c.CommandType = adCmdText

db.Errors.Clear c.Execute

If db.Errors.Count > 0 Then WriteError

End If End Sub

Once is okay, twice isn’t: Since this routine creates a table in your database, run-ning it a second tim e w ill fail unless you rem ove the table m anually. You should use a query tool to delete the table before you try it a second tim e or try it again to see the error that w ill result from executing this com m and tw ice.

The ro utine begins by c reating a new instanc e o f the Commando bjec t and setting the ActiveConnectionpro perty to the same Connectiono bjec t I c reated in Chapter 12. Then I assign the SQL statement I want to exec ute to the CommandTextpro perty. Sinc e I’m exec uting an SQL statement, I’ll set the CommandTypeto adCmdTextto prevent the server fro m trying to determine if it is the name o f a table o r sto red pro c edure.

Onc e the c o mmand is defined, exec uting is easy. I Clearthe Errorsc o llec tio n to make sure that any erro rs in the c o llec tio n are c aused b y the Executemetho d. Then I use the Executemetho d to run the c o mmand o n the datab ase server. If there are any erro rs in the Errorsc o llec tio n, I’ll c all the WriteErrorro utine to display the info rmatio n.

Returning a Recordset

Wo rking with Recordsetsis basic ally the same as wo rking with simple c o mmands exc ept that the Executemetho d returns a referenc e to Recordseto bjec t. In Listing 13-2, I c reate a Connectiono bjec t the same way as in Listing 13-1, but instead o f the Cre ate TableSQL statement, I use a Se le ctstatement.

(15)

Listing 13-2:

The Command4_Click event in Command Demo

c.CommandText = “Select Count(*) From Customers Where State = ‘MD’”

StatusBar1.SimpleText = “Response: “ & _ FormatNumber(rs.Fields(0).Value, 0) End If

End Sub

Sinc e the c all to c.Executewill return an o bjec t referenc e, I need to use a Set statement to assign the o bjec t referenc e to the Recordseto bjec t. No te that I didn’t need to c reate an instanc e o f the Recordseto bjec t. The Executemetho d to o k c are

Quick and dirty: Building and debugging a database application can be difficult. If you’re truly paranoid, like m e, you don’t trust your application until you can verify that it w orked properly using an independent tool. This is w here a tool like SQL Server’s Query Analyzer com es in handy. You can use it to execute any type of query you like. Thus, you can test your Selectstatem ent to ensure that the right num ber of row s w as returned or to verify that an update to the database w as m ade properly. You can also use it to test various SQL statem ents, and w hen you’re satisfied that they’re correct, you can copy them to the CommandText prop-erty of a Commandobject.

(16)

Running with parameters

While kno wing the number o f c usto mers in Maryland is nic e, a better appro ac h than c reating a Commando bjec t fo r eac h state wo uld be to c reate o ne that ac c epts parameters. This is also an easy pro c ess, as yo u c an see in Listing 13-3. This ro utine is based o n the o ne sho wn in Listing 13-2. The o nly differenc es are the o nes needed fo r parameters.

Listing 13-3:

The Command3_Click event in Command Demo

Private Sub Command3_Click() Dim c As ADODB.Command Dim p As ADODB.Parameter Dim rs As ADODB.Recordset On Error Resume Next Set c = New ADODB.Command Set c.ActiveConnection = db

c.CommandText = “Select Count(*) From Customers Where State = ?”

c.CommandType = adCmdText

Set p = c.CreateParameter(“State”, adChar, adParamInput, 2) c.Parameters.Append p

c.Parameters(“State”).Value = Text3.Text db.Errors.Clear

Set rs = c.Execute

If db.Errors.Count > 0 Then WriteError

Else

StatusBar1.SimpleText = “Response: “ & _ FormatNumber(rs.Fields(0).Value, 0) End If

End Sub

(17)

Next, I use the CreateParametermetho d to c reate a new Parametero bjec t c alled State. I’ll save the o bjec t referenc e in a tempo rary variable c alled p. It has a type o f

Char(2)and is an input-o nly parameter. The last argument o f the metho d is o mitted. Had I wanted to assign a default value fo r the parameter, I wo uld have spec ified it as the last parameter. After c reating the parameter, I use the Appendmetho d o f the Parametersc o llec tio n to add the o bjec t to the c o llec tio n.

Order in the parameters: The order in w hich you add the param eters to the col-lection is the sam e order that w ill be used to m atch the param eters to the ques-tion m arks in the CommandText. The first param eter is m apped to the first question m ark, w hile the second param eter is m apped to the second question m ark, and so on.

Onc e the parameter has b een defined, yo u c an use the Parametersc o llec tio n to identify the parameter b y name and assign it a value. Then yo u c an use the Executemetho d to generate the Recordseto b jec t and display the results.

An alternate way to exec ute a c o mmand with parameters is to supply the parame-ter values as part o f the Executemetho d, as sho wn in the fo llo wing line o f c o de:

Set rs = c.Execute(, Array(Text3.Text))

The sec o nd argument o f the Executemetho d allo ws yo u to spec ify a Variant array c o ntaining a list o f parameters that will be used by the c o mmand. The easiest way to c o nstruc t a Variantarray is to use the Arrayfunc tio n, whic h takes a list o f values and returns a Variantarray c o ntaining the values. If yo u have already spec i-fied a parameter direc tly in the Parametersc o llec tio n, the value spec ified in the Executemetho d will o verride that value.

Stored Procedures

Sto red pro c edures are useful to o ls that allo w yo u to exec ute a set o f SQL state-ments o n the database server by issuing a single c o mmand with a series o f parame-ters. Info rmatio n c an be returned via the Parametersc o llec tio n o r in a Recordset o bjec t. Sto red pro c edures are highly dependent o n the database system o n whic h they run. Ho wever, the benefits o f using sto red pro c edures o ften far o utweigh hav-ing SQL statements that are independent o f a partic ular database system.

Advantages of stored procedures

Many peo ple use sto red pro c edures in their database applic atio ns fo r three main reaso ns: faster perfo rmanc e, applic atio n lo gic , and sec urity.

(18)

Faster performance

Using sto red pro c edures is typic ally faster than issuing the eq uivalent SQL state-ments fro m yo ur applic atio n, fo r several reaso ns. The first reaso n is that sto red pro c edures are sto red o n the datab ase server in a prepared fo rmat. This avo ids the o verhead o f preparing a statement o n the fly. Also , if yo u repeatedly exec ute the same statement, mo st datab ase servers will prepare the statement eac h time yo u exec ute it, impo sing a lo t o f extra o verhead o n the datab ase server.

Prepared for speed: Before any SQL statem ent can be executed, it m ust be pre-pared. Preparing a statem ent involves parsing the w ords in the statem ent, com pil-ing them into a package, and then optim izpil-ing the package based on the data in the database.

In additio n, sto red pro c edures o ften c o ntain multiple SQL statements, whic h means that yo u do n’t have to wait fo r a respo nse ac ro ss the netwo rk befo re yo u send the next c o mmand. The individual statements are exec uted in sequenc e until the sto red pro c edure is c o mplete. This means that the intermediate rec o rdsets yo u wo uld have transmitted to the c lient c o mputer, and the c o mmands yo u wo uld have issued in respo nse, aren’t nec essary. Whic h in turn reduc es the amo unt o f time needed to perfo rm the func tio n.

Application logic

Sto red pro c edures are written using a language that allo ws yo u to have lo c al vari-ab les, perfo rm c o mputatio ns, c all o ther sto red pro c edures, and pro c ess rec o rd-sets — as well as exec ute SQL statements. In sho rt, yo u c an think o f a sto red pro c edure muc h like yo u wo uld think o f a Visual Basic pro gram, b ut o ne who se exec utio n is tightly c o upled with the datab ase server.

Sinc e many develo pers find this c o nc ept appealing, they c o de their b usiness lo gic as sto red pro c edures and make them availab le fo r applic atio n pro grammers to use. This ensures that eac h pro gram c an take advantage o f the b usiness lo gic , and as lo ng as the c alling seq uenc e isn’t c hanged, yo u wo n’t have to rec o mpile yo ur Visual Basic pro gram eac h time a sto red pro c edure is c hanged.

Security

Using a sto red pro c edures c an be mo re sec ure than granting so meo ne direc t ac c ess to a database. Sinc e sto red pro c edures are database o bjec ts, they are usually sec ured using the same to o ls that yo u wo uld use fo r a table o r a view fo r user ac c ess, yet yo u c an allo w the sto red pro c edure to run using so meo ne else’s database privileges. This allo ws yo u to put c o de in a sto red pro c edure to perfo rm a spec ific func tio n that the user might no t o therwise be able to perfo rm. The user will no t be able to see o r c hange this c o de.

(19)

Stored procedures and the Data View Window

In Chapter 9, I talked abo ut ho w to use the Data View Windo w ( see Figure 13-2) to ac c ess yo ur database while using the Data Enviro nment Designer. It’s po ssible to use the Data View Windo w witho ut the Data Enviro nment Designer. Unlike the Data Enviro nment Designer, the Data View Windo w isn’t integrated into yo ur pro gram. It is a design-time o nly to o l that allo ws yo u to ac c ess yo ur database design, tables, views, and sto red pro c edures tasks using a database vendo r independent to o l.

Figure 13-2: Adding the Data View Window to your application

Exclusively Enterprise Edition: The Data View Window features I’m going to cover apply to the Enterprise Edition of Visual Basic. If you have the Professional Edition, you w ill need to create and debug your stored procedures using tools provided by your database vendor. This isn’t entirely bad, as I feel these tools are often better than the ones supplied w ith Visual Basic.

Creating a Data Link

Befo re yo u c an use the Data View Windo w, yo u need to c reate a link to the database. After o pening the Data View Windo w, right c lic k o n the Data Link ic o n and selec t Add a Data Link fro m the po p-up menu. This will display the same Data Link Pro perties dialo g bo x that yo u’ve seen many times by no w (see Figure 13-3). Simply selec t the pro per OLE DB pro vider fo r yo ur database, enter the c o nnec tio n info rmatio n, and press OK to return to the Data View Windo w.

(20)

Figure 13-3: View ing the Data Link Properties w indow yet again

Creating a stored procedure

If yo u expand yo ur newly c reated Data Link ic o n, yo u’ll see eac h o f the fo ur types o f o bjec ts available fo r yo u to manipulate: Database Diagrams, Tables, Views and Sto red Pro c edures. Do uble c lic king o n the Sto red Pro c edures ic o n will display the list o f sto red pro c edures in the database, and right c lic king o n the same ic o n and selec ting New Sto red Pro c edure fro m the po up menu will allo w yo u to c reate a new sto red pro -c edure (see Figure 13-4).

The New Sto red Pro c edure windo w is a simple edito r with a series o f b utto ns ac ro ss the to p o f the sc reen. The same windo w will b e used to edit an existing sto red pro c edure. The o nly differenc e is that the name o f the existing sto red pro -c edure will b e displayed in the title b ar. The i-c o ns that appear in the to o lb ar are explained b elo w:

Ne w Store d Proce dure – pro mpts yo u to save yo ur c hanges and then dis-plays a skeleto n sto red pro c edure fo r yo u to edit.

Ope n Te xt File – asks if yo u want to o verwrite the existing text and then dis-plays a File Open dialo g bo x to lo ad a text file into the edit windo w.

(21)

Figure 13-4: Creating a stored procedure

Save as Te xt– saves yo ur sto red pro c edure to a text file.

Print – sends yo ur sto red pro c edure to the default Windo ws printer.

Find – displays a Find dialo g bo x.

Cut/ Copy/ Paste – perfo rms the standard editing func tio n using the c lipbo ard.

De bug – starts the sto red pro c edure debugger.

Coding the stored procedure

Writing a sto red pro c edure is highly dependent o n the database server yo u use. The example I’m go ing to use here is fo r the SQL Server 7. Ho wever, no matter who se database system yo u’re using, all sto red pro c edures have so me things in c o mmo n. First, they are all c reated using theCre ate Proce dureSQL statement, and c an be

New Stored Procedure Save to

Database Print

Cut Paste

Open Text File Save as Text

Find Copy

(22)

deleted with the Drop Proce durestatement. The identifier that fo llo ws the Cre ate Proce durestatement is the name o f the sto red pro c edure. Sec o nd, all sto red pro c e-dures ac c ept arguments that allo w yo u to pass parameters to them and return val-ues fro m them. After the arguments are defined, yo u enter the statements that c o mprise the sto red pro c edure.

The Sto red Pro c edure windo w allo ws yo u to build the Cre ate Proce durestatement that will c reate yo ur sto red pro c edure. Listing 13-4 sho ws a sto red pro c edure that perfo rms the same func tio n as the Se le ctstatement I’ve been using thro ugho ut this c hapter in the sample pro gram. It takes a single parameter, @Statethat has a type o f Char(2), whic h is the same type as the State c o lumn in the database. The @State parameter is used in plac e o f the questio n mark in the parameterized Se le ct state-ment in the previo us example.

Listing 13-4:

The CountByState stored procedure

Create Procedure CountByState (@State Char(2)) As Select Count(*)

From Customers Where State = @State Return

Saving the stored procedure

Pressing the Save to Database butto n will exec ute the Create Procedurestatement o n the database server and will c reate a sto red pro c edure using the name CountByState. If yo u want to edit the sto red pro c edure, simply expand the Sto red Pro c edures ic o n o n the Data View windo w and do uble c lic k o n CountByName. This will display the same SQL statement, with o ne mino r differenc e. The wo rds Create Procedurewill be replac ed with Alter Procedure.

Debugging stored procedures

The T-SQL Debugger allo ws yo u to debug sto red pro c edures direc tly fro m Visual Basic . This to o l o nly wo rks with SQL Server 6.5 and later databases. The debugger c an be c alled direc tly fro m Visual Basic . Befo re yo u c an use the debugger, yo u must install the appro priate c o de o n yo ur database server.

Installing the SQL Server debugging support

(23)

When yo u start the setup pro gram, yo u’ll see a dialo g bo x similar to the o ne sho wn in Figure 13-5 reminding yo u that this utility is no t part o f SQL Server, but part o f Visual Basic . If yo u agree with the lic ense info rmatio n, press the Co ntinue butto n.

Figure 13-5: Review ing license inform ation for the SQL Server Debugging facility

The next few dialo g bo xes will ask yo u to verify yo ur name and o rganizatio n info r-matio n and to enter the CD Key fro m the bac k o f yo ur Visual Basic CD-ROM c ase. Enter the info rmatio n as requested and press OK o r Co ntinue at eac h step o f the wizard until yo u reac h the Installatio n dialo g bo x sho wn in Figure 13-6. Yo u c an c hange the direc to ry where the so ftware will be installed by pressing the Change Fo lder butto n. When yo u’re ready to begin, press the square Server butto n. The setup pro gram will then install the debugging suppo rt feature.

(24)

I got this weird error: If you get a strange error w hile trying to start the T-SQL Debugger and it instructs you to look in the client log on the database server, m ost likely the SQL Server Debugging support has not been installed.

Setting T-SQL Debugging Options

Befo re yo u use the T-SQL Deb ugger, yo u sho uld review the o ptio ns. To display the o ptio ns, c ho o se To o ls➪T-SQL Deb ugging Optio ns fro m the Visual Basic main menu. This will b ring up the T-SQL Deb ugging Optio ns dialo g b o x, as sho wn in Figure 13-7.

Figure 13-7: Setting debugging options

There are fo ur o ptio ns yo u c an set. Chec king the Auto matically ste p into Sto re d Pro ce dure s thro ugh RDO and ADO co nne ctio nswill auto matic ally start the debugger anytime yo u exec ute a sto red pro c edure while running yo ur Visual Basic pro gram. If this bo x is no t c hec ked, the debugger will no t be used at runtime. Chec king Use Safe Mo de ( transactio n ro llback) fo r Sto re d Pro ce dure callsmeans that any c hanges made by the sto red pro c edure while in debug mo de are disc arded.

Sometimes it works and sometimes it doesn’t: I’ve noticed that changing these properties don’t alw ays take effect the next tim e you run your program in the IDE. I suggest running your program and ending it before you attem pt to do anything. Then run the program again, and the debugger should behave properly.

The Limit SQL Output to the fo llo wing numbe r o f line s pe r re sultse tdetermines the upper limit in the number o f ro ws that will be retrieved while debugging the pro c e-dure. This value helps to ensure that yo ur sto red pro c edure do esn’t run o ut o f c o n-tro l. The Lo gin Time o ut value fo r re trie ving sto re d pro ce dure te xtsets the maximum amo unt o f time the debugger will wait to c o nnec t to the database server.

Starting the T-SQL Debugger

Yo u c an run the SQL Debugger direc tly fro m Visual Basic by c ho o sing Add-Ins ÿ T-SQL Debugger fro m the main menu. This will display the Visual Basic T-T-SQL Batc h Debugger dialo g bo x ( see Figure 13-8) . Yo u need to pro vide the info rmatio n in this windo w to c o nnec t to the database to selec t and run yo ur sto red pro c edure. Note

(25)

Figure 13-8: Setting options in the T-SQL Debugger w indow

To c o nnec t to an SQL Server database using OLE DB, simply enter the name o f yo ur database server in the SQL Server dro p-do wn bo x, spec ify the name o f the database yo u want to use in the Database dro p do wn bo x, and supply yo ur user name and passwo rd in the UIDand Passwo rdfields. Yo u c an also define an ODBC c o nnec tio n by pressing the Define DSN butto n.

Onc e these values are set, the Sto red Pro c edure and Batc h Query tabs will be enabled. To debug a sto red pro c edure, selec t the Sto red Pro c edure tab ( see Figure 13-9) and c ho o se the sto red pro c edure yo u want to debug in the Pro c edure Name dro p-do wn bo x. Then selec t eac h o f the parameters listed in the Parame te rsarea and assign them the values yo u want to use during the exec utio n.

(26)

Run simple queries: You can use the Batch Query tab in the Visual Basic T-SQL Debugger to run any block of SQL statem ents you m ay choose using the T-SQL Debugger.

Running the Debugger

After yo u have finished entering values fo r all o f the parameters, press the Exec ute butto n o n the Sto red Pro c edure tab o f the Visual Basic Batc h T-SQL Debugger to start a debugging sessio n. The T-SQL Debugger windo w will be displayed ( see Figure 13-10) .

Figure 13-10: Running the T-SQL Debugger

Local Variables and Parameters

Status Global Variables Results Stored Procedure Select Query

Toggle Breakpoint Run to Cursor Step Over Step Info

Remove all Breakpoints Go

(27)

Se le ct Que ry– allo ws yo u to c ho o se fro m multiple queries yo u may be debug-ging at the same time.

Go– runs the query to c o mpletio n fro m the c urrent statement o r to the next breakpo int.

Toggle Bre akpoint– enables o r disables a breakpo int at the spec ified line o f c o de.

Re move s All Bre akpoints – remo ves all o f the breakpo ints in the sto red pro c edure.

Ste p Into – runs the sto red pro c edure until the spec ified subexpressio n is reac hed

Ste p Ove r – runs the selec ted subexpressio n.

Run To Cursor – runs the sto red pro c edure up to where the c urso r is po inting.

Store d Proce dure – c o ntains the text o f the sto red pro c edure. This area is used to display the c urrently ac tive statement and any breakpo ints that have been set.

Local Variable s and Parame te rs – this sec tio n c o ntains variables lo c al to the sto red pro c edure and their c urrent values. Yo u c an edit a value by do uble c lic king o n the value to selec t it and entering a new value.

Global Variable s– this sec tio n c o ntains the glo bal variables fo r the sto red pro c edure and their c urrent values. These values may also be c hanged while the sto red pro c edure is waiting fo r user input.

Re sults – displays any ro ws returned by a Se le ct statement and also desc ribes the c urrent state o f exec utio n.

Status –desc ribes the c urrent state o f the debugger. If the message Waiting fo r use r inputis displayed, the debugger is in break mo de and waiting fo r yo u to resume exec utio n.

Calling a stored procedure

As yo u might expec t, defining a sto red pro c edure in a Commando b jec t isn’t muc h different than defining an SQL statement ( see Listing 13-5) . In plac e o f the SQL statement, yo u will need to spec ify the name o f the sto red pro c edure in the CommandTextpro perty. Yo u sho uld spec ify adCmdStoredProcas the value o f CommandType.

(28)

Listing 13-5:

The CountByState stored procedure

Private Sub Command6_Click() Dim c As ADODB.Command Dim p As ADODB.Parameter Dim rs As ADODB.Recordset On Error Resume Next Set c = New ADODB.Command Set c.ActiveConnection = db c.CommandText = “CountByState” c.CommandType = adCmdStoredProc c.Parameters.Refresh

c.Parameters(“@State”).Value = Text4.Text db.Errors.Clear

Set rs = c.Execute

If db.Errors.Count > 0 Then WriteError

Else

StatusBar1.SimpleText = “Response: “ & _ FormatNumber(rs.Fields(0).Value, 0) End If

End Sub

Thoughts on Stored Procedures

Using stored procedures is very im portant w hen building applications for Oracle. They can m ake a significant difference in how your application perform s. How ever, stored proce-dures are not as im portant for SQL Server 7 databases. SQL Server 7 prepares an SQL state-m ent the first tistate-m e it encounters it during your prograstate-m ’s execution and retains it so that the next tim e you use it, it w on’t have to prepare it again. This doesn’t m ean that you shouldn’t use stored procedures in SQL Server 7, because they don’t m ake as big of a dif-ference as they do w ith an Oracle database.

(29)

Summary

In this c hapter yo u learned the fo llo wing:

✦Yo u c an define a Commando bjec t to ho ld a frequently exec uted SQL statement o r sto red pro c edure.

✦Yo u c an define Parametero bjec ts whic h c o ntain info rmatio n that is passed to a sto red pro c edure o r parameterized query fo r exec utio n.

✦Yo u c an easily c reate and edit sto red pro c edures direc tly in Visual Basic .

✦Yo u c an install the sto red pro c edure debugger ro utines into yo ur database server so that yo u c an debug sto red pro c edures direc tly fro m Visual Basic .

(30)

Gambar

Table 13-1Properties of the Command Object
Table 13-2Values for CommandType
Table 13-4Values for Options
Table 13-6Properties of the Parameter Object
+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

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

Puji syukur kami panjatkan kepada Tuhan Yang Maha Esa atas limpahan rahmat dan hidayah-Nya sehingga Prosiding Seminar Nasional MIPA Universitas Negeri Yogyakarta

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: