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

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

51 317 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

Định dạng
Số trang 51
Dung lượng 1,58 MB

Nội dung

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. Connection Object 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 client/server system. Connection Properties Property Name Description Attributes This returns or sets the characteristics of a connection. The valid attributes for a connection include the following constants: adXactCommitRetaining—ensures that calling CommitTrans will automatically start a new transaction; adXactAbortRetaining— ensures that calling RollbackTrans will automatically start a new transaction. CommandTimeout This specifies how many seconds to wait while executing a command before returning 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. ConnectionString Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com (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 provider- specific file that contains connection information; 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. ConnectionTimeout This indicates how many seconds to wait when creating a connection to a data source before the connection attempt fails with an error. The default value is 15 seconds. You can only set this property when a connection is closed; it is read- only when a connection is open. CursorLocation This allows you to choose between various cursor libraries for a provider. Typically, you can either choose a client-side cursor library 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 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. DefaultDatabase This string specifies the default database for a connection. If a default database is set, SQL strings may access objects in that database using an unqualified syntax. IsolationLevel Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 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. Mode The Mode property is used to set or get the access permissions used by the provider for a database connection. The property can only be set when the Connection is closed. The valid values for the Mode property are: 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 permissions. Provider This string can be used to set or get the name of the provider for the database connection. It is read-only when a connection is open and read/write when it is closed. It can also be set using the ConnectString property or the ConnectString parameter for the Connection.Open() method. The default provider is the Microsoft OLE DB Provider for ODBC (MSDASQL). State This returns the state of the Connection object. 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. Version This returns the version number of the ADO objects that are in use. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Connection Methods Method Name Description BeginTrans() This begins a new transaction for the database connection. Within a transaction, no changes to the database are committed until 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" transaction is committed. Close() This closes the current database connection and any active Recordsets associated with the connection. CommitTrans() This saves any database changes and ends the current transaction. It may also begin a new transaction depending on the Connection.Attributes property settings. Execute(Command, RecsAffected, Options) This executes a database command. 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. Open(ConnectString, User, PW) Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 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. OpenSchema(QueryType, Criteria, SchemaID) This returns a RecordSet containing database schema information from the datasource provider. QueryType specifies the type of schema query to run, and Criteria is an array of values that may be used to limit the results for the query type. There are three QueryTypes that are required by the OLE DB specification: adSchemaTables, 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. QueryType Criteria Constants adSchemaColumns TABLE_CATALOG TABLE_SCHEMA TABLE_NAME COLUMN_NAME adSchemaProviderTypes DATA_TYPE BEST_MATCH adSchemaTables TABLE_CATALOG TABLE_SCHEMA TABLE_NAME TABLE_TYPE RollbackTrans() This ends the current transaction and cancels any changes. Depending on the Connection.Attributes property, it may al so begin a new transaction. Caution 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 Connection Collections Collection Name Description Errors This contains a collection of Error objects generated by a provider when a failure occurs. Properties This contains a collection of Property objects associated with an ADO object. This may be used by a provider to supplement the st andard ADO properties with dynamic properties. Connection Code Sample 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 Microsoft SQL Server 6.5. Note 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. Listing 16.1 Connect1.vbs ’ FILE: Connect1.vbs ’ DESC: This shows basic usage of the Connection object. ’ AUTH: Thomas L. Fredell ’ DATE: 10/31/1998 ’ ’ Copyright 1998 Macmillan Publishing ’ Dim connection Dim sConnectionString ’ My connection string is hardcoded to a Microsoft SQL Server database sConnectionString = "driver={SQL Server};server=TLFSRV1;uid=sa;" & _ "pwd=;database=pubs" Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Set connection = WScript.CreateObject("ADODB.Connection") connection.ConnectionString = sConnectionString connection.Open If Err.Number <> 0 Then Wscript.Echo "Err# " + Err.Number + " - " + Err.Description Else Wscript.Echo "Connected to pubs database using <" + connection.Provider + ">." End If Figure 16.5 illustrates the results of running the connect1.vbs script. Figure 16.5: The results of running the connect1.vbs script. 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 OpenSchema() method: Note 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 in your WSH scripts. Listing 16.2 Connect2.vbs ’ FILE: Connect2.vbs ’ AUTH: Thomas L. Fredell ’ DESC: This illustrates how you can use an ADO Connection through ’ WSH and VBScript to access a database and display Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com information ’ about the tables in the database. ’ DATE: 10/31/1998 ’ ’ Copyright 1998 Macmillan Publishing ’ ’ ADO Constants ’ ’ NOTE: Have to copy these in because WSH can’t dynamically ’ include files at runtime. ’ Const adSchemaTables = 20 ’ ’ Check parameters ’ If Wscript.Arguments.Count <> 5 Then ’ Show the usage Wscript.Echo "USAGE: connect2.vbs [driver] [server] [user]" & _ "[password] [database]" Wscript.Echo "" Wscript.Echo " Connects to a database and displays" & _ "information about" Wscript.Echo " the tables within the database." ’ And quit Wscript.Quit 0 End If Dim sDriver, sServer, sUser, sPassword, sDatabase Dim sConnect Dim connDb Dim rsetTables Dim sTablesListing Dim oShell ’ ’ Get parameters for connection ’ sDriver = Wscript.Arguments(0) sServer = Wscript.Arguments(1) sUser = Wscript.Arguments(2) sPassword = Wscript.Arguments(3) sDatabase = Wscript.Arguments(4) ’ Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ’ Create connection string ’ sConnect = "driver=" + sDriver + ";server=" + sServer + ";uid=" + _ sUser + ";pwd=" + sPassword + ";database=" + sDatabase ’ ’ Now attempt to open the connection ’ On Error Resume Next Set connDb = WScript.CreateObject("ADODB.Connection") connDb.ConnectionString = sConnect connDb.Open If Err.Number <> 0 Then ShowErr "Unable to connect to database." End If WScript.Echo "Connected to ’" + sDatabase + "’ on ’" + sServer + "’" ’ ’ Use the connection to get the table schema ’ Set rsetTables = connDb.OpenSchema(adSchemaTables) If Err.Number <> 0 Then ShowErr "Unable to open the schema." End If ’ ’ Now retrieve and dump the table listing ’ sTablesListing = "" Do While Not rsetTables.EOF sTablesListing = sTablesListing & rsetTables.Fields(2) & _ Chr(10) & Chr(13) If Err.Number <> 0 Then ShowErr "An error occurred." rsetTables.MoveNext Loop Set oShell = Wscript.CreateObject("Wscript.Shell") oShell.Popup sTablesListing, 0, "Table listing from ’" & sDatabase & "’" ’ ’ Quit with no error ’ Wscript.Quit 0 ’ Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ’ SUBR: ShowErr(sDesc) ’ DESC: Displays information about the current error then quits. ’ Sub ShowErr(sDesc) Wscript.Echo "Error: " & sDesc Wscript.Echo "Err# " & Err.Number & " - " & Err.Description Wscript.Quit Err.Number End Sub 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. Figure 16.6: The results of running the connect2.vbs script. Command Object 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. Command Properties Property Name Description ActiveConnection This is the connection for the Command object. It is a read-write property and may be set using either a Connection object or a Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... long binary; adLongVarChar—the field value is a long String value; adLongVarWChar—the field value is a long nullterminated string value; adNumeric—the field value is a fixed precision and scale numeric value; adSingle—the field value is a single-precision floating point; adSmallInt—the field value is a 2-byte signed integer; adTinyInt—the field value is 1-byte; adUnsignedBigInt—the field value is an 8- byte... 8- byte unsigned integer; adUnsignedInt—the field value is a 4byte unsigned integer; adUnsignedSmallInt—the field value is a 2-byte unsigned integer; adUnsignedTinyInt—the field value is a 1-byte unsigned integer; adUserDefined—the field value is user-defined; adVarBinary—the field value is binary; adVarChar—the field value is a String; adVariant— the field value is a Variant; adVector—this indicates that... This indicates the edit status for the current record It will be one of the following constants: adEditNone—this indicates that 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.à à This indicates the type of lock that should be placed on records when editing It may be one of the following... à Recordset Code Sampleà à 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.à à à à à à Ãà à Noteà 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... HelpContextÃà This returns the context ID for the topic in the Windows help file indicated in the HelpFile property.à à HelpFileà This returns a string that contains the fully resolved path for a Windows help file.à à à NativeErrorÃà ÃThis returns a provider-specific error code.à Numberà à This indicates which error occurred.à à Sourceà à This is a string that indicates the ADO object that generated the error.Ã... it.à à à à à à à à Delete(Index)Ãà This deletes a Parameter from the collection using either the ordinal position in the collection or the parameter name.à à Item(Index)à à This retrieves a Parameter from the collection using either the ordinal position in the collection or the name.à à Refreshà à This retrieves provider-side parameter information for the query specified in the Command object associated... This returns a boolean value that indicates whether the provider supports all the options specified in the CursorOptions parameter 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... 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... query against a database; Figure 16.7 illustrates the results of running the script. à à à à à à à à à à à Figure 16.7: The results of running the command1.vbs script. à à à Ãà à à à Listing 16.3 Command1.vbsà à ’ FILE: Command1.vbsà ’ AUTH: Thomas L Fredellà ’ DESC: This illustrates how you can use an ADO Command throughà ’ WSH and VBScript to run a command against a database.à ’ DATE: 10/31/19 98 ’à ’... 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—the field value is an 8- byte signed integer; adBinary—the field value is binary; adBoolean—the field value is a boolean; adByRef—this is Or'd together with another one of the data type constants and indicates that the field value is a pointer to . connect1.vbs script. Figure 16.5: The results of running the connect1.vbs script. The preceding example is simple and shows only the most basic code involved in connecting to a database using WSH. include the following constants: adXactCommitRetaining—ensures that calling CommitTrans will automatically start a new transaction; adXactAbortRetaining— ensures that calling RollbackTrans. & Err.Description Wscript.Quit Err.Number End Sub When I run the script using cscript connect2.vbs "{SQL Server}" TLFSRV1 sa "" pubs for the command line, the script runs,

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

TỪ KHÓA LIÊN QUAN