1. Trang chủ
  2. » Công Nghệ Thông Tin

sams teach Yourself windows Script Host in 21 Days phần 8 pot

51 322 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Connection Object
Trường học Standard University
Chuyên ngành Computer Science
Thể loại Bài viết
Năm xuất bản 2023
Thành phố New York
Định dạng
Số trang 51
Dung lượng 1,58 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The connection string may contain the following parameters: Provider—this specifies the name of the OLE DB provider; Data Source—this specifies the name of a registered data source; User

Trang 1

more about the capabilities of the Connection object, including support for

transactions, in the documentation for the Connection object later in this

chapter.







The last major ADO object that you need to understand is the Command

object The Command object represents a SQL statement, a table name, or a

stored procedure You can use it as a convenient way to call a stored

procedure that you might use multiple times; it has methods and properties

that allow you to describe the characteristics of the stored procedure Later

in the chapter, you can find more details about the Command object, and you

can see examples of its usage.









The ADO objects are easy to use from WSH, and you can exploit them for

numerous purposes Any time you need to retrieve, store, or modify data,

you can use the ADO objects to go directly to a database system In this

chapter you’ll see reference information for each object; make sure that you

review the examples for the objects because they’ll show you basic usage of

the objects from ADO After the reference material for each object, we’ll take

a step back and review some of the ways that you can use ADO from WSH

to perform useful tasks.

The Connection object is the root of the ADO object hierarchy It

represents a connection to an OLE DB data source The connection may be

the equivalent of an actual network connection to a database server in a

adXactCommitRetaining—ensures that calling CommitTrans will automatically start a new transaction; adXactAbortRetaining—

ensures that calling RollbackTrans will automatically start a new transaction.

Trang 2

(DSN) or a connection string with embedded parameters The DSN may be any registered datasource The connection string may contain the following parameters: Provider—this specifies the name of the OLE DB provider; Data Source—this specifies the name of a registered data source; User ID—this is the user ID to use for the connection; Password—this specifies the password to use when opening the connection;

File Name—this is the name of a specific file that contains connection information;

provider-Remote Provider—this is the name of the provider to use when opening a client-side connection if the Remote Data Service is being used; Remote Server—this specifies the path name of the server to use when opening a connection using the Remote Data Service.

property when a connection is closed; it is only when a connection is open.

connections that are established after the property is set If the connection is open, this property is read-only; if it is closed, the property is read/write The valid constants for this property are: adUseClient—this uses the client-side cursor engine, the Microsoft Client Cursor Provider, which provides special features such as disassociated recordsets;

adUseClientBatch—this has the same effect

as adUseClient; adUseServer—this is the default, which indicates that data provider or driver-supplied cursors should be used.

Trang 3

uncommitted changes in other transactions;

adXactReadUncommitted—this has the same function as adXactBrowse;

adXactCursorStability—this is the default isolation level, which means that from one transaction you can only view committed changes from other transactions;

adXactReadCommitted—this has the same function as adXactCursorStability;

adXactRepeatableRead—this indicates that from one transaction you cannot see changes made in other transactions, but that requerying can bring new recordsets; adXactIsolated—

this indicates that transactions are isolated from other transactions; adXactSerializable—this has the same function as adXactIsolated.

adModeUnknown—this is the default mode and indicates that the permissions haven't been set or can't be determined adModeRead—this indicates read-only; adModeWrite—this indicates write-only; adModeReadWrite—this indicates read/write is allowed; adModeShareDenyRead—

this prevents others from opening a connection with read capabilities;

adModeShareDenyWrite—this prevents others from opening a connection with write capabilities;

adModeShareExclusive—this prevents others from opening a connection;

adModeShareDenyNone—this prevents others from opening new connections with any

It will be one of the following constants:

adStateClosed—this is the default setting, which indicates that the object is closed;

adStateOpen—this indicates that the object is open.





Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 4

CommitTrans() is called Any changes within the transaction established by BeginTrans() can be rolled back using RollbackTrans()

When BeginTrans() is called as a function, it returns a Long indicating the level of nesting of the transaction With some providers, you can nest transactions No nested transactions are actually committed until the "outermost"

Connection.Attributes property settings.

Execute() may either be used as a statement, such as connection.Execute "DELETE * FROM Authors WHERE LastName LIKE

’A’", or as a function returning a RecordSet, such as Set recordset =

connection.Execute("SELECT * FROM Authors") The first parameter, Command, is the database command that you want to execute

The second, RecsAffected, is a Long value that will contain the number of rows affected by the command, if supported by the provider The Options parameter indicates how the provider should evaluate the command; it may be one of the following constants: adCmdText—this indicates that the provider should evaluate CommandText as a text command;

adCmdTable—this indicates that the CommandText specifies a table name;

adCmdStoredProc—this indicates that CommandText specifies a stored procedure;

adCmdUnknown—this indicates that the type of command is unknown.

Trang 5

Open(ConnectString, User, PW) 



datasource The ConnectString parameter must specify a valid datasource connection string The User parameter is the username for the datasource connection, and PW is the password.

adSchemaColumns, and adSchemaProvider These QueryType and the corresponding Criteria constants are listed in the following table There are many other QueryTypes; check the Microsoft ADO documentation for additional listings The final parameter, SchemaID, may be used to specify

a GUID for a provider-specific schema query.

Connection.Attributes property, it may also begin a new transaction.

You can specify the username and password using either the

Open() parameters or within the connection string, but don’t

specify it in both places or the results will be unpredictable.





Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 6

First we’ll begin with a simple example that shows you how you can use the

Connection object to connect to a database The following example

instantiates a connection and then connects to a hard-coded database The

example in Listing 16.1 uses the standard pubs database that comes with

All the examples for the ADO objects use the Microsoft SQL

Server pubs database example If you do not have access to the

pubs database or SQL Server, just substitute a different relational

database—or even a simple database such as Access—that you

have handy The only thing that you need to change is the SQL

query and the datasource connection strings If you run the

samples, you'll need to change the connection strings anyway to

reference your database server.

Trang 7

The preceding example is simple and shows only the most basic code

involved in connecting to a database using WSH and ADO Listing 16.2

shows a more sophisticated example that uses a Connection object to

open a database and display all the tables in the database using the

You’ll notice that there are some inline constants at the beginning

of my code Those constants were pulled from the adovbs.inc

file that comes with ADO The file contains all the ADO constants

Unfortunately, WSH doesn’t have a file inclusion mechanism—so I

can't just include the contents of adovbs.inc at runtime There's

also a corresponding file for JavaScript called adojavas.inc

You'll need those files if you plan to use any of the ADO constants

’ WSH and VBScript to access a database and display

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 9

 ’ Create connection string 

Trang 10

When I run the script using cscript connect2.vbs "{SQL Server}"

TLFSRV1 sa "" pubs for the command line, the script runs, connects to

the database, retrieves the table names, and then displays a dialog box

containing the list of names Figure 16.6 shows the output from the script.

The Command object represents a specific command that you want to

execute against a datasource It may be a straight SQL statement, a

parameterized query, or a stored procedure You can use it to do a query

and retrieve a recordset, to change the database structure, to execute a bulk

change—anything that you can do with a standard database command.



Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 11

valid connection string If a connection string

is used, the provider will create a new Connection object using the definition.

an error and terminating the command request The default value is 30 seconds If a command doesn’t complete execution within the number of seconds specified by

CommandTimeout, ADO will cancel the command and raise an error If you set CommandTimeout to zero, ADO will wait indefinitely for the command to complete.

adCmdStoredProc—this evaluates the command as a stored procedure;

adCmdUnknown—this indicates that the type

of command is unknown If you know what type of command you will use, setting the CommandType will increase the speed of ADO's execution because it doesn't have to determine the type of the command at runtime.

(compiled) version of the command specified

by CommandText Some providers may not support this property and will either return an error or ignore the value if you change the Prepared property.

It will be one of the following constants:

adStateClosed—this is the default setting, which indicates that the object is closed;

adStateOpen—this indicates that the object

Trang 12

Execute() may either be used as a statement, such as command.Execute RecCount, or as a function returning a recordset, such as Set recordset = command.Execute() The first parameter, RecsAffected, is a Long value that will contain the number of rows affected by the command, if supported by the provider The Parameters parameter is a Variant array

of parameter values that should be used with the Command; they may override parameters that are in the Command.Parameters collection The Options parameter indicates how the provider should evaluate the command; it may be one of the following constants: adCmdText—this indicates that the provider should evaluate CommandText

as a text command, like a SQL statement;

adCmdTable—this indicates that the command specifies a table name;

adCmdStoredProc—this indicates that command specifies a stored procedure;

adCmdUnknown—this indicates that the type

When you call CreateParameter(), the new Parameter object

is not automatically added to the Command.Parameters

collection If you want to, you must add it manually to the

Parameters collection using the Parameters.Add() method.

If your command uses output parameters, you must specify the

parameters using Parameter objects in the

Command.Parameters collection You can't pass output

parameters in the Parameters argument to the Execute()

Trang 13

The script given in Listing 16.3, Command1.vbs, provides a simple example

illustrating how you can use the Command object to run a query against a

database; Figure 16.7 illustrates the results of running the script.

Trang 14

 sConnectionString = "driver={SQL Server};server=TLFSRV1;uid=sa;" & _ 

The Recordset object represents the results of executing a database

command You can use a Recordset to retrieve and page through

information returned by a command, you can use it to add new rows to a

table, and you can use it to change data within a table When you create a

Recordset, you can walk through the Recordset using navigation

methods such as MoveNext() and MovePrevious() See the following

sections for more details regarding the use of recordsets.

on which the current record is located

AbsolutePage is 1-based like AbsolutePosition It may either return a page number or one of the following

constants: adPosUnknown—this indicates that the current position is unknown;

adPosBOF—this indicates that the record pointer is at BOF (Beginning Of File);

adPosEOF—this indicates that the record pointer is at EOF (End Of File).

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 15

object It is a read-write property and may be set using either a Connection object or a valid connection string If a connection string

is used, the provider will create a new Connection object using the definition.

see the CursorType property for more details.

or a server-side library This setting only affects database connections that are established after the property is set If the connection is open, this property is read-only;

if it is closed, the property is read/write The valid constants for this property are:

adUseClient—this uses the client-side cursor engine, the Microsoft Client Cursor Provider, which provides special features such





Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 16

generate reports—any changes made by other users are not visible.

no edits are in progress;

adEditInProgress—this indicates that data

in the current record has been modified;

adEditAdd—this indicates that AddNew() has been invoked.

adFilterNone—this removes the current filter; adFilterPendingRecords—this allows you to view only records that have changed but have not yet been committed (this only applies to batch update mode);

adFilterAffectedRecords—this allows you to view only records affected by the last Delete, Resync, UpdateBatch, or CancelBatch call;

adFilterFetchedRecords—this allows you to view records from the results of the last call to retrieve records from the database.

of the following constants:

adLockReadOnly—this is the default, indicating read-only; adLockPessimistic—

this specifies pessimistic locking, which the provider typically implements by locking the record at the datasource immediately upon editing; adLockOptimistic—this specifies optimistic locking, which the provider typically implements by locking records only when Update() is called;

adLockBatchOptimistic—this specifies optimistic batch updates and is required for batch update mode.

is the default, indicating that all rows are returned to the server;

adMarshalModifiedOnly—this indicates that only modified rows are returned.

Trang 17

 MaxRecords 



This may be used to specify the maximum number of rows returned by the provider If this property is zero, all requested rows will be returned.

to get a string representing the current datasource This is read-only for open Recordsets and read-write for closed Recordsets.

adStateClosed—this is the default setting, which indicates that the object is closed;

adStateOpen—this indicates that the object

It may be one of the following values:

adRecOK—indicates that the record was successfully updated; adRecNew—indicates that the record is new; adRecModified—

indicates that the record was modified;

adRecDeleted—indicates that the record was deleted; adRecUnmodified—indicates that the record was not modified;

adRecInvalid—indicates that the record was not saved because its bookmark is invalid; adRecMultipleChanges—indicates that the record was not saved because it would affect multiple records;

adRecPendingChanges—indicates that the record was not saved because it refers to a pending insert; adRecCanceled—indicates that the record was not saved because the operation was canceled;

adRecCantRelease—indicates that the new record was not saved because of record locks; adRecConcurrencyViolation—

indicates that the record was not saved 



Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 18

because optimistic concurrency was in force;

adRecIntegrityViolation—indicates that the record was not saved because integrity constraints were violated;

adRecMaxChangesExceeded—indicates that the record was not saved because of too many pending changes;

adRecObjectOpen—indicates that the record was not saved because of a conflict with an open storage object;

adRecOutOfMemory—indicates that the record was not saved because the computer has run out of memory;

adRecPermissionDenied—indicates that the record was not saved because the user has insufficient permissions;

adRecSchemaViolation—indicates that the record was not saved because it violates the database structure; adRecDBDeleted—

indicates that the record has already been deleted.

Be careful when you use the RecordCount property

Depending on the capabilities of the provider and datasource, all

records may have to be retrieved and counted to return an

accurate count value.

be used to create a new record The Fields argument can contain a field name, an array

of field names, or an array of integers indicating positions in the record The Values argument can either be a single Variant value or an array of Variants The number

of Fields specified must match the number

of Values, but both parameters are optional.

 

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 19

is set to one of the valid predefined constants; adAffectAll—this is the default, which cancels pending updates for all the records in the Recordset, even if they are hidden by the Filter.

a new Recordset using the same command parameters Only Recordsets that support bookmarks can be cloned.

AffectRecords parameter may be used to determine which records will be affected It may be one of the following constants:

adAffectCurrent—this is the default, which deletes just the current record;

adAffectGroup—this deletes all the records that satisfy the current Filter property setting, if the Filter is set to one of the predefined constants.

The Rows parameter is a Long indicating the number of rows to retrieve; it defaults to the constant adGetRowsRest, which returns the rest of the rows from the Recordset Start

is an optional parameter that specifies the bookmark for the record from which GetRows() should begin retrieving records It may be a bookmark or one of the following constants: adBookmarkCurrent—this starts

at the current record; adBookmarkFirst—

this starts at the first record;

adBookmarkLast—this starts at the last record Fields is an optional parameter that specifies the fields whose values should be retrieved by GetRows() It may be a single field name, an array of field names, a positional field index, or an array of indices.

This moves the position of the current record

NumRecords specifies how many record positions to move; if it is positive, it moves forward through the recordset, and if it is





Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 20

either as a bookmark or as one of the following constants: adBookmarkCurrent—

this starts at the current record;

adBookmarkFirst—this starts at the first record; adBookmarkLast—this starts at the last record.

RecordsAffected is an optional parameter into which the provider will return the number

of records affected by the command or stored procedure.

Source is an optional Variant that





Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 21

adCmdUnknown—this indicates that the type

adAffectCurrent—this refreshes just the current record; adAffectGroup—this refreshes the records that satisfy the current Filter, if it is set to one of the predefined constants; and adAffectAll—this is the default, which refreshes all the records in the Recordset Calling Resync() does not cause the underlying Recordset command

CursorOptions is a Long value that may consist of one or more of the following constant values (combined using the VBScript Or operator or the JavaScript |):

adAddNew indicates that AddNew() may be used to add new records;

adApproxPosition indicates that AbsolutePosition and AbsolutePage can be set; adBookmark indicates that you can use the Bookmark property; adDelete indicates that you can delete records using Delete(); adHoldRecords indicates that you can retrieve more records or change the next position without committing all pending changes; adMovePrevious indicates that you can use MoveFirst(),

MovePrevious(), Move(), and GetRows(); adResync indicates that you can use Resync(); adUpdate indicates that you can use Update();

adUpdateBatch indicates that you can use batch updating via UpdateBatch() and CancelBatch().

to the current record of the Recordset You can use the Fields and Values arguments

to specify values that should be set during the Update() call The Fields argument can contain a field name, an array of field names,

or an array of integers indicating positions in the record The Values argument can either

be a single Variant value or an array of Variants The number of Fields specified must match the number of Values, but both parameters are optional.

Trang 22

UpdateBatch(AffectRecords)



This writes all pending batch changes to the underlying database

AffectRecords is an optional parameter that specifies which records should be affected It may be one of the following constants:

adAffectCurrent—this writes changes only for the current record;

adAffectGroup—this writes changes for the records that match the current Filter setting, if it is one of the predefined Filter constants; and adAffectAll—this is the default, which writes changes for all the records in the Recordset object.

The script shown in Listing 16.4, recset1.js, provides a simple example

illustrating how you can use the Recordset object to run a query and view

the query results.

This script example is implemented using the JScript language As

emphasized earlier in this book, you can use either JScript or

VBScript for your WSH scripting tasks The language is obviously

different, but you still use the objects—in this case ADO—the

Trang 23

 // DESC: This demonstrates basic usage of the Recordset object. 

 Listing 16.4 shows how easy it is to use the Recordset object to retrieve

and navigate a result set Figure 16.8 shows the result of running the script. 





Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 24

The Field object represents a column of data retrieved in a result set Field

objects are stored in the Recordset.Fields collection You can use them

to retrieve field values, get information about field values such as the

numeric precision, or change existing field values.





Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 25

tracking; adFldCacheDeferred—this indicates that the provider caches field values, so subsequent reads come from the cache.

This returns the type of the Field value It may be one

of the following constants: adArray—this indicates that the data is a safe-array and will be Or'd together with one of the other data type constants; adBigInt—





Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Ngày đăng: 13/08/2014, 08:21

TỪ KHÓA LIÊN QUAN