57
Програмиране с А Програмиране с А DO DO Общ преглед на Общ преглед на ADO ADO обектния модел обектния модел книга книга Programming ADO Programming ADO

Програмиране с А DO Общ преглед на ADO обектния модел книга Programming ADO

  • Upload
    sailor

  • View
    55

  • Download
    0

Embed Size (px)

DESCRIPTION

Програмиране с А DO Общ преглед на ADO обектния модел книга Programming ADO. Connection Object Open and Close methods ADO has no collection object in its object model containing all of the Connection objects. BeginTrans, CommitTrans, and RollbackTrans - PowerPoint PPT Presentation

Citation preview

Page 1: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Програмиране с АПрограмиране с АDODOОбщ преглед на Общ преглед на ADO ADO обектния модел обектния модел

книга книга Programming ADOProgramming ADO

Page 2: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Connection Object• Open and Close methods • ADO has no collection object in its object model containing all of the Connection

objects.• BeginTrans, CommitTrans, and RollbackTrans• OpenSchema method lets you view much of the metadata about your database. • ADO's events on the Connection object will fire to signify the completion of the

asynchronous call. • To determine why your query failed, you can evaluate the Errors collection of the

Connection object.• Execute method to submit queries, including queries that generate Recordsets. • Execute method also allows you to issue an action query to modify data, manipulate

objects, or change database-specific settings on your database.Command Object

• help your work with queries that you'll execute repeatedly or queries that will check the value of an output or return parameter on a call to a stored procedure.

• You can submit the query to your database via the Command object's Execute method.

• you can issue an action query or a query that will return a Recordset. • ActiveCommand property on the Recordset object refers back to the Command

object used to open that Recordset. • Command object's Parameters collection work with parameterized queries and

stored procedures. • The ActiveConnection property on the Command object refers back to the

Connection object.

Page 3: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Recordset ObjectRecordset Object* * contains the results of your query. contains the results of your query. * Each column is stored in a Field object in the Recordset's Fields collection. * Each column is stored in a Field object in the Recordset's Fields collection. * Open* Open method of the Recordset object retrieve the results of a query either through the method of the Recordset object retrieve the results of a query either through the Command object or directly through the Connection object. Command object or directly through the Connection object. * You can also generate a Recordset object by calling the * You can also generate a Recordset object by calling the ExecuteExecute method on either the method on either the Connection or Command object. Connection or Command object. * The Recordset's ActiveConnection property refers to the Connection object that the * The Recordset's ActiveConnection property refers to the Connection object that the Recordset uses to communicate with the database. Recordset uses to communicate with the database. * ActiveCommand property refers to the Command object that generated the Recordset * ActiveCommand property refers to the Command object that generated the Recordset

Dynamic Properties• ADO's Properties collection contains Property objects that store

information about database system features.• Different database systems expose different features. For example,

secure Microsoft Access databases require a system database file (System.mdw). Microsoft SQL Server has options for using standard or integrated security. ODBC API calls to take advantage of the unique features of your particular database system. ADO Properties collection is reserved for provider-specific features.

Page 4: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Obtaining a Recordset Without a Command ObjectObtaining a Recordset Without a Command Object

If you are not going to execute your query more than once, you If you are not going to execute your query more than once, you probably don't need to use a Command object:probably don't need to use a Command object:

strConn = "Provider=SQLOLEDB;Data Source=MyServer;" & _ strConn = "Provider=SQLOLEDB;Data Source=MyServer;" & _                "Initial Catalog=Northwind;" & _          "Initial Catalog=Northwind;" & _          

"User ID=MyUserID;Password=MyPassword;“"User ID=MyUserID;Password=MyPassword;“Set cnNorthwind = New ADODB.ConnectionSet cnNorthwind = New ADODB.ConnectioncnNorthwind.Open strConn cnNorthwind.Open strConn 

strSQL = "SELECT * FROM Customers“strSQL = "SELECT * FROM Customers“Set rsCustomers = New ADODB.RecordsetSet rsCustomers = New ADODB.RecordsetrsCustomers.Open strSQL, cnNorthwindrsCustomers.Open strSQL, cnNorthwind

Page 5: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Connection Object: To Use or Not to UseConnection Object: To Use or Not to UseYou might find that sometimes the only reason you use your Connection object You might find that sometimes the only reason you use your Connection object is to open Recordset objects. is to open Recordset objects.

• strConn = "Provider= SQLOLEDB;Data Source=MyServer;" & _"Initial Catalog=Northwind;" & _

          "User ID=MyUserID;Password=MyPassword;“strSQL = "SELECT * FROM Customers“Set rsCustomers = New ADODB.RecordsetrsCustomers.Open strSQL, strConn

ActiveConnection parameter

Page 6: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

But proceed with caution! do you want the ActiveConnection property on each But proceed with caution! do you want the ActiveConnection property on each of your Recordset objects to refer to the same Connection object?of your Recordset objects to refer to the same Connection object?

Set rsCustomers = New ADODB.RecordsetSet rsCustomers = New ADODB.RecordsetrsCustomers.Open "SELECT * FROM Customers", strConnrsCustomers.Open "SELECT * FROM Customers", strConnSet rsOrders = New ADODB.RecordsetSet rsOrders = New ADODB.RecordsetrsOrders.Open "SELECT * FROM Orders", strConnrsOrders.Open "SELECT * FROM Orders", strConn

• each Recordset object was opened using the same connection string to communicate with the same database;

• separate Connection object for each Recordset.• Each Connection objects maintains its own physical

connection to the database.

Page 7: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

1. 1. explicitly create a Connection object and use it with both Recordset objects:explicitly create a Connection object and use it with both Recordset objects:Set cnNorthwind = New ADODB.ConnectionSet cnNorthwind = New ADODB.ConnectioncnNorthwind.Open strConncnNorthwind.Open strConnSet rsCustomers = New ADODB.RecordsetSet rsCustomers = New ADODB.RecordsetrsCustomers.Open "SELECT * FROM Customers", cnNorthwindrsCustomers.Open "SELECT * FROM Customers", cnNorthwindSet rsOrders = New ADODB.RecordsetSet rsOrders = New ADODB.RecordsetrsOrders.Open "SELECT * FROM Orders", cnNorthwinrsOrders.Open "SELECT * FROM Orders", cnNorthwin

2. 2. one Connection object,( without having to explicitly create one) using one Connection object,( without having to explicitly create one) using ActiveConnection property on the initial Recordset object for both of them:ActiveConnection property on the initial Recordset object for both of them:Set rsCustomers = New ADODB.RecordsetSet rsCustomers = New ADODB.RecordsetrsCustomers.Open "SELECT * FROM Customers", strConnSet rsCustomers.Open "SELECT * FROM Customers", strConnSet rsOrders = New ADODB.RecordsetrsOrders = New ADODB.RecordsetrsOrders.Open "SELECT * FROM Orders", _  rsOrders.Open "SELECT * FROM Orders", _  

            rsCustomers.ActiveConnection            rsCustomers.ActiveConnection

• This (p.2) will improve the performance of your queries &

• control the number of actual connections you're making to the database.

Page 8: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Obtaining a Recordset Without a DatabaseObtaining a Recordset Without a Database1.1. Microsoft developed the ODBC cursor library. Microsoft developed the ODBC cursor library. 2. Microsoft Visual Basic 5 users could retrieve the results of a query into this 2. Microsoft Visual Basic 5 users could retrieve the results of a query into this library and actually disconnect from the database and later reconnect to their library and actually disconnect from the database and later reconnect to their databases to update.databases to update.3. Remote Data Services (RDS), provided early versions of ADO with a cursor 3. Remote Data Services (RDS), provided early versions of ADO with a cursor engine. This technology allowed ADO to pass a recordset across process engine. This technology allowed ADO to pass a recordset across process boundaries. boundaries. 4. Beginning with ADO 2.0, recordsets can be persisted to a file and reopened 4. Beginning with ADO 2.0, recordsets can be persisted to a file and reopened later. later. 5. You can also create your own recordset by taking a Recordset object 5. You can also create your own recordset by taking a Recordset object variable and populating the Fields collection yourself.variable and populating the Fields collection yourself.

Disconnecting a Recordset from a Connection• disconnected recordsets - open a connection to your database,

retrieve data, close the connection, work with the data, and reopen the connection when you want to communicate with your database again.Use ActiveConnection property of the Recordset object :

Page 9: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

'Open a connection to your database.'Open a connection to your database.Set cnDatabase = New ADODB.ConnectionSet cnDatabase = New ADODB.ConnectioncnDatabase.CursorLocation = adUseClientcnDatabase.CursorLocation = adUseClientcnDatabase.Open strConn, strUserID, strPasswordcnDatabase.Open strConn, strUserID, strPassword

'Make the query and retrieve the results.'Make the query and retrieve the results.Set rsData = New ADODB.RecordsetSet rsData = New ADODB.RecordsetrsData.Open strSQL, cnDatabase, adOpenStatic, _ rsData.Open strSQL, cnDatabase, adOpenStatic, _            adLockBatchOptimistic, adCmdTextSet            adLockBatchOptimistic, adCmdTextSet rsData.ActiveConnection = NothingrsData.ActiveConnection = Nothing

'Close your connection'Close your connection..cnDatabase.ClosecnDatabase.Close

'Modify your recordset.'Modify your recordset.

'Reopen your connection.'Reopen your connection.cnDatabase.OpencnDatabase.Open'Point your recordset at your connection.'Point your recordset at your connection.Set rsData.ActiveConnection = cnDatabaseSet rsData.ActiveConnection = cnDatabase

'Submit the changes from the recordset to your database.'Submit the changes from the recordset to your database.rsData.UpdateBatchrsData.UpdateBatch

Page 10: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

ActiveConnection = Nothing ADO Cursor Engine to dissociate the Recordset object from the Connection object.

• reconnect to the database Open method of the Connection object,

• associate the Recordset with the Connection object, • submit the changes in the Recordset to the database by calling the

UpdateBatch .

Page 11: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Persistence Can Pay OffPersistence Can Pay Off

ADO 2.0 introduced functionality that makes it possible to store database information on ADO 2.0 introduced functionality that makes it possible to store database information on the desktop without having a desktop database. ADO Recordset object has a the desktop without having a desktop database. ADO Recordset object has a SaveSave method method

'Retrieve the results of your query and save them to a file. The path to the file'Retrieve the results of your query and save them to a file. The path to the file' and the filename are stored in the string  strPathToOrdersFile.' and the filename are stored in the string  strPathToOrdersFile.Set cnDatabase = New ADODB.ConnectionSet cnDatabase = New ADODB.ConnectionSet rsOrders = New ADODB.RecordsetSet rsOrders = New ADODB.RecordsetrsOrders.Open strSQL, cnDatabase, adOpenStatic, _rsOrders.Open strSQL, cnDatabase, adOpenStatic, _              adLockBatchOptimistic, adCmdText              adLockBatchOptimistic, adCmdTextrsOrders.Save strPathToOrdersFilersOrders.Save strPathToOrdersFile

'Retrieve the contents of the file into a Recordset,'Retrieve the contents of the file into a Recordset,' modify the Recordset accordingly, and then save the changes back to a file.' modify the Recordset accordingly, and then save the changes back to a file.rsOrders.Open strPathToOrdersFile, , , _rsOrders.Open strPathToOrdersFile, , , _              adLockBatchOptimistic, adCmdFile              adLockBatchOptimistic, adCmdFilersOrders.AddNewrsOrders.AddNewrsOrders.UpdatersOrders.UpdatersOrders.Save strPathToOrdersFilersOrders.Save strPathToOrdersFile'Retrieve the contents of the file into a Recordset & submit the changes to your database'Retrieve the contents of the file into a Recordset & submit the changes to your database..rsOrders.Open strPathToOrdersFile, , , _rsOrders.Open strPathToOrdersFile, , , _              adLockBatchOptimistic, adCmdFile              adLockBatchOptimistic, adCmdFileSet rsOrders.ActiveConnection = cnDatabaseSet rsOrders.ActiveConnection = cnDatabasersOrders.UpdateBatchrsOrders.UpdateBatch

Page 12: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

The ADO Connection ObjectThe ADO Connection Object• Connection Object Properties and Collections

Prop. or Coll. Name Data Type DescriptionAttributes Long Controls the behavior of the Connection object

after CommitTrans or RollbackTrans has been called CommandTimeout Long Sets the length of time that queries on this connection can run before timing out ConnectionString String Specifies how to connect to your database ConnectionTimeout Long Sets the length of time that ADO will wait before

an attempt to connect to your db times out CursorLocation Long Sets the default value for the location of the cursor for Recordsets opened on this Connection object DefaultDatabase String When connecting to Microsoft SQL Server and

other database servers that expose multiple databases, specifies which database to use

Errors Collection of Error objects Each Error object contains information about an error that occurred on the Connection

object IsolationLevel Long Controls the level at which transactions for the

database are isolated Mode Long Sets the permissions for modification of the Connection object Properties Collection of Property objects Stores information about provider-specific properties for

the Connection object Provider String OLE DB provider nameState Long Current state (open or closed) of the Connection object

Version String Version of ADO

Page 13: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

IsolationLevel PropertyIsolationLevel PropertyYou can use the IsolationLevel property to control the isolation level of the You can use the IsolationLevel property to control the isolation level of the transactions on your Connection object. The property can be set to any one of the transactions on your Connection object. The property can be set to any one of the IsolationLevelEnum values listed:IsolationLevelEnum values listed:

IsolationLevelEnum Values Constant Value Description adXactUnspecified -1 Indicates that the provider is using an

isolation level that cannot be determined adXactBrowse, adXactReadUncommitted 256 Allows you to view changes pending in

another transaction Subject to nonrepeatable reads and phantom rows

adXactCursorStability, adXactReadCommitted 4096 Default; ensures that your transaction does

not view any pending updates Subject to nonrepeatable reads and phantom rows, but immune to dirty reads

adXactRepeatableRead 65536 Ensures that your transaction does not view any pending updates and that rows you read

are not modified by other transactions Subject to phantom rows

adXactIsolated, adXactSerializable 1048576 Specifies complete isolation from other

transactions

Page 14: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

ADO Connection Object Functions and MethodsADO Connection Object Functions and Methods

Connection Object Functions and Methods Function or Method Name Description

BeginTrans Initiates a transactionCancel Cancels an asynchronous attempt to

connect to your databaseClose Closes the connection to your

databaseCommitTrans Commits the current transactionExecute Submits a query to your databaseOpen Opens a connection to your databaseOpenSchema Retrieves schema information from your databaseRollbackTrans Rolls back the current transaction

Page 15: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Connection.Execute CommandText, RecordsAffected, Options Connection.Execute CommandText, RecordsAffected, Options

cnDatabase.Execute "DELETE FROM MyTable WHERE ID = 7“cnDatabase.Execute "DELETE FROM MyTable WHERE ID = 7“ By default, the By default, the ExecuteExecute method on the Connection object returns a Recordset method on the Connection object returns a Recordset object:object:

'Create a new Recordset.'Create a new Recordset.Set rsResults = New ADODB.RecordsetSet rsResults = New ADODB.Recordset'Set the Recordset to use a keyset cursor and optimistic locking.'Set the Recordset to use a keyset cursor and optimistic locking.'These settings make the Recordset updatable'These settings make the Recordset updatable.rsResults.CursorType = adOpenKeyset.rsResults.CursorType = adOpenKeysetrsResults.LockType = adLockOptimisticrsResults.LockType = adLockOptimistic'Call Connection.Execute and retrieve a new, nonupdatable Recordset object.'Call Connection.Execute and retrieve a new, nonupdatable Recordset object.Set rsResults = cnDatabase.Execute(strSQL)Set rsResults = cnDatabase.Execute(strSQL)

if you want to maintain any control over the Recordset object generated by if you want to maintain any control over the Recordset object generated by your query, use the your query, use the OpenOpen method on the Recordset object rather than the method on the Recordset object rather than the ExecuteExecute method of the Connection object. method of the Connection object.The best use of the The best use of the ExecuteExecute method is for action queries—queries that will not method is for action queries—queries that will not return a recordsetreturn a recordset

Page 16: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

OpenOpen Method MethodYou use the You use the OpenOpen method to connect to your database. method to connect to your database.

ConnectionConnection.Open .Open ConnectionStringConnectionString, , UserIDUserID, , PasswordPassword, , OptionsOptions  

OpenSchemaOpenSchema Method Methodprovide a list of tables and the names of the fields in each table. You might even want to provide a list of tables and the names of the fields in each table. You might even want to retrieve foreign key constraints to show relationships within the database. The retrieve foreign key constraints to show relationships within the database. The OpenSchemaOpenSchema method returns a Recordset object to help you retrieve this type of information:method returns a Recordset object to help you retrieve this type of information:

SetSet Recordset Recordset =  = ConnectionConnection.OpenSchema .OpenSchema QueryTypeQueryType, , CriteriaCriteria, , SchemaIDSchemaID

The current documentation for adSchemaColumns lists four available restrictions: The current documentation for adSchemaColumns lists four available restrictions: TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, and COLUMN_NAME.:TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, and COLUMN_NAME.:

Dim rsSchema As ADODB.RecordsetDim rsSchema As ADODB.RecordsetDim aRestrictions As VariantDim aRestrictions As Variant

aRestrictions = Array(Empty, Empty, "Customers", Empty)aRestrictions = Array(Empty, Empty, "Customers", Empty)Set rsSchema = cnDatabase.OpenSchema(adSchemaColumns,  aRestrictions)Set rsSchema = cnDatabase.OpenSchema(adSchemaColumns,  aRestrictions)

Page 17: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

ADO Connection Object EventsADO Connection Object Events

The connection object raises the events listed in the following table.The connection object raises the events listed in the following table.

Connection Object Events Connection Object Events Event NameEvent Name DescriptionDescriptionBeginTransCompleteBeginTransComplete Fires when the Fires when the BeginTransBeginTrans method completes method completesCommitTransCompleteCommitTransComplete Fires when the Fires when the CommitTransCommitTrans method completes method completesConnectCompleteConnectComplete Fires when the attempt to connect completesFires when the attempt to connect completesDisconnectDisconnect Fires when the Fires when the CloseClose method completes method completesExecuteCompleteExecuteComplete Fires when the Fires when the ExecuteExecute method completes method completesInfoMessageInfoMessage Returns informational error messagesReturns informational error messagesRollbackTransCompleteRollbackTransComplete Fires when the Fires when the RollbackTransRollbackTrans method completes method completesWillConnectWillConnect Fires when the Fires when the OpenOpen method on the Connection method on the Connection

object is called, prior to the attempt to connect to the object is called, prior to the attempt to connect to the databasedatabase

WillExecuteWillExecute Fires prior to submitting a query to the Connection Fires prior to submitting a query to the Connection object with the Execute method or when the Open object with the Execute method or when the Open method is called on a Recordset associated with the method is called on a Recordset associated with the Connection objectConnection object

Page 18: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Anatomy of a Connection StringAnatomy of a Connection String

• The OLE DB Provider For ODBC DriversADO communicates with your database by means of an OLE DB provider. ADO 2.0 and later ship with native OLE DB providers for Access, SQL Server, and Oracle databases.

• if you don't have a native OLE DB provider? As long as you have an ODBC driver that supports basic ODBC functionality, you should still be able to use ADO. The OLE DB Provider For ODBC Drivers makes ODBC API calls that ask the driver what functionality it supports.

• The OLE DB Provider for Access Databases"Provider=Microsoft.Jet.OLEDB.4.0;  Data Source=C:\Path\To\MyDatabase.MDB;“

The OLE DB Provider For SQL Server Databases"Provider=SQLOLEDB;Data Source=MyServer;    Initial Catalog=MyDatabase;    User ID=MyUID;Password=MyPassword;“

• The OLE DB Provider For Oracle Databasescommunicate with Oracle's client components rather than directly with the Oracle database. In order to use ADO with Oracle, you have to install the appropriate version of the Oracle client utilities (SQL*Net) and create a database alias. Once you've done that, you can use a connection string such as this:

"Provider=MSDAORA;Data Source=MyDatabaseAlias;    User ID=MyUID;Password=MyPassword;"

Page 19: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Managing Your TransactionsManaging Your Transactions

BeginTrans, CommitTrans, and RollbackTransBeginTrans, CommitTrans, and RollbackTrans Methods Methods

On Error Resume NextOn Error Resume Next'Start the transaction.'Start the transaction.cnDatabase.BeginTranscnDatabase.BeginTransstrSQL = "UPDATE Savings SET BalDue = BalDue - 50 " & "WHERE AccountNumber = 123456789“strSQL = "UPDATE Savings SET BalDue = BalDue - 50 " & "WHERE AccountNumber = 123456789“cnDatabase.Execute strSQLcnDatabase.Execute strSQLIf cnDatabase.Errors.Count > 0 Then    If cnDatabase.Errors.Count > 0 Then    

'An error occurred, cancel changes.   'An error occurred, cancel changes.   cnDatabase.RollbackTranscnDatabase.RollbackTrans

Else   Else      strSQL = "UPDATE Checking SET BalDue = BalDue + 50 " & _             strSQL = "UPDATE Checking SET BalDue = BalDue + 50 " & _             

“WHERE AccountNumber = 123456789"    “WHERE AccountNumber = 123456789"    cnDatabase.Execute strSQL    cnDatabase.Execute strSQL    If cnDatabase.Errors.Count > 0 Then        If cnDatabase.Errors.Count > 0 Then        

'An error occurred, cancel all of the changes.        'An error occurred, cancel all of the changes.        cnDatabase.RollbackTrans    cnDatabase.RollbackTrans    

Else        Else        ‘No errors occurred, commit all of the changes.        ‘No errors occurred, commit all of the changes.        cnDatabase.CommitTrans    cnDatabase.CommitTrans    

End IfEnd IfEnd IfEnd If

Page 20: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

IsolationLevel PropertyIsolationLevel Property

• Definitions of Some Transactional Terms

• dirty read When one transaction reads uncommitted changes from another transaction.

• nonrepeatable read When data read in transaction A is modified by transaction B before transaction A completes.

• phantom row When transaction A examines the results of a query and then transaction B inserts a row that satisfies the

criteria for transaction A's query before transaction A completes. This term comes from the fact that in this case,

transaction A could run the same query twice and see a new row appear mysteriously (like a phantom) in the second set of results.

• SQL Server supports all four isolation levels ( Read Committed - default). You can set the ADO Connection object's IsolationLevel property to use any of the four SQL-92 isolation levels.

SQL-92 Isolation Levels Dirty Read Nonrep Read Phant. RowRead Uncommitted Yes Yes YesRead Committed No Yes YesRepeatable Read No No YesSerializable No No No

Page 21: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

The ADO Recordset and Field Objects The ADO Recordset and Field Objects ADO Recordset Object Properties and CollectionsADO Recordset Object Properties and Collections

• Recordset Object Properties and CollectionsProperty or Coll. Name Data Type Description ActiveCommand Variant Pointer to the Command object that created the

Recordset object ActiveConnection String or Connection Connection object used to retrieve

the results of your query CacheSize Long number of records cached from the server (1)CursorLocation Long the location of the cursor (either client-side or

server-side) CursorType CursorTypeEnum the type of cursor DataSource Object Allows you to bind the Recordset to a data

source Fields Collection of Field objects Pointer to the collection of Field objects that

contain the results of your query Filter Variant Allows you to filter your RecordsetLockType LockTypeEnum Specifies how the contents of your Recordset

can be locked and updatedMaxRecords Long the maximum number of records to be returned PageCount Long Returns the number of pages in your Recordset PageSize Long number of records per page in your Recordset RecordCount Long Returns the number of records in the Recordset Sort String Allows you to reorder the data in your Recordset Status RecordStatusEnum Returns the update status of the current record

Page 22: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Some Details about properties & collectionsSome Details about properties & collections

CursorType PropertyCursorType Property

CursorTypeEnum Values CursorTypeEnum Values ConstantConstant ValueValue DescriptionDescription adOpenForwardOnlyadOpenForwardOnly 0 0 Default for server-side Recordsets; opens a Default for server-side Recordsets; opens a

Recordset that supports scrolling forward only Recordset that supports scrolling forward only adOpenStatic adOpenStatic 33 Default and only possible value for client-side Default and only possible value for client-side

Recordsets; supports scrolling forward and Recordsets; supports scrolling forward and backward; changes made by other users are backward; changes made by other users are

not visible not visible adOpenKeyset adOpenKeyset 1 1 Supports scrolling forward and backward; Supports scrolling forward and backward;

modifications and deletions by other users are modifications and deletions by other users are visible visible

adOpenDynamic adOpenDynamic 2 2 Supports scrolling forward and backward; Supports scrolling forward and backward; modifications, deletions, and insertions made modifications, deletions, and insertions made by other users are visible by other users are visible

Page 23: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Fields CollectionFields Collection

In the following Visual Basic code, all lines are equivalent to each other, In the following Visual Basic code, all lines are equivalent to each other, referring to the Value property for the CustomerID field in the referring to the Value property for the CustomerID field in the rsCustomersrsCustomers Recordset object (assuming CustomerID is the first field in the Recordset):Recordset object (assuming CustomerID is the first field in the Recordset):

rsCustomers.Fields("CustomerID").ValuersCustomers.Fields("CustomerID").ValuersCustomers.Fields(0).ValuersCustomers.Fields(0).ValuersCustomers(0).ValuersCustomers(0).ValuersCustomers("CustomerID").ValuersCustomers("CustomerID").ValuersCustomers.Fields("CustomerID")rsCustomers.Fields("CustomerID")rsCustomers.Fields(0)rsCustomers.Fields(0)rsCustomers(0)rsCustomers(0)rsCustomers("CustomerID")rsCustomers("CustomerID")

Page 24: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Filter Property – which records in Recordset to viewFilter Property – which records in Recordset to viewyou can set the property to a string or to a value in FilterGroupEnumyou can set the property to a string or to a value in FilterGroupEnum

FilterGroupEnum ValuesFilterGroupEnum Values ConstantConstant ValueValue DescriptionDescription adFilterNone adFilterNone 0 0 Default; clears the current filter Default; clears the current filter adFilterPendingRecords 1 adFilterPendingRecords 1 Displays only the records with Displays only the records with

pending changes pending changes adFilterAffectedRecords 2 adFilterAffectedRecords 2 Displays only the records affected Displays only the records affected

by the last call to by the last call to DeleteDelete, , ResyncResync, , UpdateBatchUpdateBatch, or , or CancelBatchCancelBatch

adFilterFetchedRecords 3 adFilterFetchedRecords 3 Displays only the records currently Displays only the records currently stored in the cache stored in the cache

adFilterConflictingRecords 5 adFilterConflictingRecords 5 Displays only the records that failed Displays only the records that failed in the last batch update attempt , in the last batch update attempt ,

because a modification from another userbecause a modification from another user

rsOrders.Filter = "CustomerID = 'ALFKI'" rsOrders.Filter = "CustomerID = 'ALFKI'"

strCriteria = "CompanyName = 'Trail''s Head Gourmet'“strCriteria = "CompanyName = 'Trail''s Head Gourmet'“rsCustomers.Filter = strCriteriarsCustomers.Filter = strCriteria

Page 25: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

LockType PropertyLockType Property

LockTypeEnum Values LockTypeEnum Values

ConstantConstant ValueValue DescriptionDescription adLockReadOnly adLockReadOnly 1 1 Default; the Recordset is read-Default; the Recordset is read-

only. only. adLockPessimistic adLockPessimistic 2 2 ADO relies on the OLE DB ADO relies on the OLE DB

provider to ensure that your provider to ensure that your update attempt will succeed.update attempt will succeed.Only 1 user/moment. Locked Only 1 user/moment. Locked for others. for others.

adLockOptimistic adLockOptimistic 3 3 The data is not locked until one The data is not locked until one call call UpdateUpdate. .

adLockBatchOptimistic 4 adLockBatchOptimistic 4 Modifications to your data are Modifications to your data are cached until you call cached until you call UpdateBatchUpdateBatch. . Designed for client side Recordsets. Designed for client side Recordsets.

Works with server side, if OLE DB provider supports the functionality Works with server side, if OLE DB provider supports the functionality (Access – not, SQL Server – yes)(Access – not, SQL Server – yes)

Page 26: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

ADO Recordset Object MethodsADO Recordset Object Methods AddNewAddNew Adds a new record to your Recordset Adds a new record to your Recordset CancelCancel Cancels an asynchronous query Cancels an asynchronous query CancelUpdateCancelUpdate Cancels pending changes on a record currently Cancels pending changes on a record currently

being edited being edited CloseClose Closes the Recordset object, releasing its contents Closes the Recordset object, releasing its contents DeleteDelete

Deletes the current record from your Recordset Deletes the current record from your Recordset FindFind Searches your Recordset for a recordsSearches your Recordset for a recordsGetRowsGetRows Returns data from your Recordset in a two-Returns data from your Recordset in a two-

dimensional Variant array dimensional Variant array GetStringGetString Returns data from your Recordset in a string Returns data from your Recordset in a string MoveMove Moves the position in Recordset Moves the position in Recordset MoveFirstMoveFirst Moves to the first record in your Recordset Moves to the first record in your Recordset MoveLastMoveLast Moves to the last record in your Recordset Moves to the last record in your Recordset MoveNextMoveNext Moves to the next record in your Recordset Moves to the next record in your Recordset MovePreviousMovePrevious Moves to the previous record in your Recordset Moves to the previous record in your Recordset NextRecordsetNextRecordset Retrieves results of the next query (RecordSet)in batch query Retrieves results of the next query (RecordSet)in batch query OpenOpen Opens the Recordset Opens the Recordset RequeryRequery Reexecutes the query that generated the Recordset Reexecutes the query that generated the Recordset SaveSave Writes the contents of the Recordset to a file Writes the contents of the Recordset to a file SeekSeek Searches the Recordset for a specified string Searches the Recordset for a specified string UpdateUpdate Writes pending changes to the RecordsetWrites pending changes to the Recordset & DB & DB unless you are unless you are

using batch update (LockType = adLockBatchOptimistic). In that case – using batch update (LockType = adLockBatchOptimistic). In that case – modifications only cashedmodifications only cashedUpdateBatchUpdateBatch from RecordSet to DBfrom RecordSet to DB

Page 27: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Examples:Examples:rsCustomers.AddNewrsCustomers.AddNewrsCustomers.Fields("CustomerID").Value = "NewID“rsCustomers.Fields("CustomerID").Value = "NewID“rsCustomers.Fields("CompanyName") = "New Customer“rsCustomers.Fields("CompanyName") = "New Customer“rsCustomers.Fields("Address").Value = "23 Highview St.“rsCustomers.Fields("Address").Value = "23 Highview St.“rsCustomers.Fields("City") = "Westwood“rsCustomers.Fields("City") = "Westwood“rsCustomers.Fields("State") = "MA“rsCustomers.Fields("State") = "MA“rsCustomers.Fields("Zip") = "02090“rsCustomers.Fields("Zip") = "02090“rsCustomers.UpdatersCustomers.Update

strCriteria = "Country = 'Germany'“strCriteria = "Country = 'Germany'“rsCustomers.Find strCriteriarsCustomers.Find strCriteriaDo While Not rsCustomers.EOF    Do While Not rsCustomers.EOF    

rsCustomers.Find strCriteria, 1rsCustomers.Find strCriteria, 1LoopLoop

strSQL = "SELECT * FROM Customers“strSQL = "SELECT * FROM Customers“rsCustomers.Open strSQL, cnDatabase, adOpenForwardOnlyrsCustomers.Open strSQL, cnDatabase, adOpenForwardOnlyDo While Not rsCustomers.EOF Do While Not rsCustomers.EOF    Debug.Print rsCustomers.Fields("CustomerID").Value   Debug.Print rsCustomers.Fields("CustomerID").Value   rsCustomers.MoveNext   rsCustomers.MoveNextLoopLoop

Page 28: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

OpenOpen Method MethodThe The OpenOpen method is the most powerful and versatile method of retrieving data method is the most powerful and versatile method of retrieving data from your database. You can set the ActiveConnection, Source, LockType, from your database. You can set the ActiveConnection, Source, LockType, and CursorType properties on the Recordset prior to using the and CursorType properties on the Recordset prior to using the OpenOpen method, method, or you can supply this data in its parameters, all of which are optional:or you can supply this data in its parameters, all of which are optional:

* * SourceSource This parameter accepts a Variant. You can use the This parameter accepts a Variant. You can use the SourceSource parameter to specify the query string or Command object parameter to specify the query string or Command object you want to use. This parameter can also contain a table you want to use. This parameter can also contain a table name, a stored procedure call, a URL, a filename. name, a stored procedure call, a URL, a filename.

ActiveConnectionActiveConnection This parameter accepts a Variant in the form of a This parameter accepts a Variant in the form of a connection string or an open Connection object, just like the connection string or an open Connection object, just like the ActiveConnection property. ActiveConnection property.

CursorType CursorType later …later … LockTypeLockType OptionsOptions CommandTypeEnum value and/or a combination of CommandTypeEnum value and/or a combination of

asynchronous ExecuteOptionEnum constantsasynchronous ExecuteOptionEnum constants

rsCustomers.Open "Customers", cnNorthwind, _ rsCustomers.Open "Customers", cnNorthwind, _ adOpenStatic, adLockReadOnly,  adCmdTable + adAsyncExecuteadOpenStatic, adLockReadOnly,  adCmdTable + adAsyncExecute

Page 29: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

ADO Recordset Object EventsADO Recordset Object Events

Event NameEvent Name DescriptionDescription EndOfRecordsetEndOfRecordset Fires when you navigate beyond the last record of Fires when you navigate beyond the last record of

data in your Recordset data in your Recordset FieldChangeCompleteFieldChangeComplete Fires after you've modified the value for a field Fires after you've modified the value for a field MoveCompleteMoveComplete Fires after the current position of the Recordset Fires after the current position of the Recordset

changes changes RecordChangeCompleteRecordChangeComplete Fires after you modify a record Fires after you modify a record RecordsetChangeCompleteRecordsetChangeComplete Fires after the Recordset object has changed Fires after the Recordset object has changed WillChangeFieldWillChangeField Fires before the contents of a field change Fires before the contents of a field change WillChangeRecordWillChangeRecord Fires before the contents of a record change Fires before the contents of a record change WillChangeRecordsetWillChangeRecordset Fires before the Recordset object changes Fires before the Recordset object changes WillMoveWillMove Fires before the current position in the Recordset Fires before the current position in the Recordset

changes changes

Page 30: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

ADO Fields Collection for RecordsetADO Fields Collection for Recordset Like all collections, the Fields collection exposes a Like all collections, the Fields collection exposes a Count propertyCount property and an and an Item Item property (the default). With the Item property, you can return a particular Field by property (the default). With the Item property, you can return a particular Field by name or index.name or index.Method NameMethod Name DescriptionDescription AppendAppend Adds a new Field ( for Recordset) to the collection (without DB) Adds a new Field ( for Recordset) to the collection (without DB)

CancelUpdateCancelUpdate Cancels the pending changes for a record Cancels the pending changes for a record DeleteDelete Deletes a Field from the collection Deletes a Field from the collection RefreshRefresh Refreshes the Fields collection Refreshes the Fields collection ResyncResync Resynchronizes the current record Resynchronizes the current record UpdateUpdate Submits the pending changes in a recordSubmits the pending changes in a recordAppendAppend Method MethodYou can use the You can use the AppendAppend method on the Fields collection to create your own method on the Fields collection to create your own Recordset object without using a database. You can populate the Fields collection Recordset object without using a database. You can populate the Fields collection with Field objects in this fashion and then call the with Field objects in this fashion and then call the Recordset.OpenRecordset.Open method to method to start adding records to your Recordset. If you're not trying to communicate with a start adding records to your Recordset. If you're not trying to communicate with a database but would like to maintain your data in a Recordset object, this method database but would like to maintain your data in a Recordset object, this method is for you. Its parameters are as follows:is for you. Its parameters are as follows:NameName TypeType DefinedSizeDefinedSize AttributesAttributes FieldValueFieldValue

Page 31: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

ADO Field Object PropertiesADO Field Object Properties

Property NameProperty Name Data TypeData Type DescriptionDescription ActualSize ActualSize Long Long Returns the actual size of a field's value Returns the actual size of a field's value Attributes Attributes Long Long Describes characteristics of the field Describes characteristics of the field DataFormat DataFormat Object Object Can be used to format your data Can be used to format your data DefinedSize DefinedSize Long Long Returns the defined size for a field Returns the defined size for a field Name Name String String Contains the name of the field Contains the name of the field NumericScale NumericScale Byte Byte Indicates the numeric scale for numeric data Indicates the numeric scale for numeric data OriginalValue OriginalValue Variant Contains the original value for the field Variant Contains the original value for the field Precision Precision Byte Byte Indicates the precision for numeric data Indicates the precision for numeric data Properties Properties Collection of Property objects Collection of Property objects Collection of dynamic Collection of dynamic

properties properties Type Type Byte Byte Returns the data type for the field Returns the data type for the field UnderlyingValue UnderlyingValue Variant Indicates the most recently retrieved value Variant Indicates the most recently retrieved value

from the database for the field from the database for the field ValueValue Variant Contains the current value for the field Variant Contains the current value for the field

Page 32: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

ADO Field Object MethodsADO Field Object MethodsMethod NameMethod Name DescriptionDescription AppendChunkAppendChunk Appends data to a large string or binary field Appends data to a large string or binary field GetChunkGetChunk Retrieves data from a large string or binary field Retrieves data from a large string or binary field

The ADO Command and Parameter ObjectsThe ADO Command and Parameter Objects This object's primary use is for repeated execution of a single query or This object's primary use is for repeated execution of a single query or multiple similar queries. The Command object exposes a Parameters multiple similar queries. The Command object exposes a Parameters collection, with each Parameter object corresponding to a parameter in a collection, with each Parameter object corresponding to a parameter in a queryqueryADO Command Object Properties and CollectionsADO Command Object Properties and CollectionsProp. or Coll. Name Data Type Prop. or Coll. Name Data Type Description Description ActiveConnection String or ConnectionSpecifies the Connection object ActiveConnection String or ConnectionSpecifies the Connection object

used to communicate with your databaseused to communicate with your databaseCommandText StringCommandText String Contains the query string or the name of the Contains the query string or the name of the

table, view, or stored procedure you want to table, view, or stored procedure you want to executeexecute

CommandTimeout LongCommandTimeout Long Controls the number of seconds the query Controls the number of seconds the query will run before timing out will run before timing out

NameName String String the name of the Command object the name of the Command object ParametersParameters Collection of Parameter objects Contains parameter Collection of Parameter objects Contains parameter

information for the query information for the query

Page 33: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

CommandType PropertyCommandType PropertyConstantConstant ValueValue DescriptionDescriptionadCmdTextadCmdText 11 The query will not be modified by ADO.The query will not be modified by ADO.adCmdTableadCmdTable 22 ADO will append "select * from " to the query.ADO will append "select * from " to the query.adCmdStoredProc4adCmdStoredProc4 ADO will format the query as a call to a stored ADO will format the query as a call to a stored

procedure; for example: procedure; for example: {? = CALL MyProc (?)}{? = CALL MyProc (?)}..

With cmdStoredProc   With cmdStoredProc    'Specify that the Command object will call a stored procedure.     'Specify that the Command object will call a stored procedure.    .CommandType = adCmdStoredProc    .CommandType = adCmdStoredProc    'Specify the stored procedure name.    'Specify the stored procedure name.    .CommandText = "MySP"    .CommandText = "MySP"    'CommandText property now contains "{ call MySP }".    'CommandText property now contains "{ call MySP }".    'Populate the Parameters collection.    'Populate the Parameters collection.    .Parameters.Append .CreateParameter("@RetVal", adInteger, _                          .Parameters.Append .CreateParameter("@RetVal", adInteger, _                                        adParamReturnValue)                  adParamReturnValue)    .Parameters.Append .CreateParameter("@Param1", adInteger, _                        .Parameters.Append .CreateParameter("@Param1", adInteger, _                                        adParamInput)                    adParamInput)    .Parameters.Append .CreateParameter("@Param2", adInteger, _                        .Parameters.Append .CreateParameter("@Param2", adInteger, _                                        adParamInput)                    adParamInput)    'CommandText property now contains "{ ? = call MySP (?, ?) }".'CommandText property now contains "{ ? = call MySP (?, ?) }".End WithEnd With

name

In/out

Page 34: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

ADO Command Object MethodsADO Command Object MethodsMethod NameMethod Name DescriptionDescriptionCancelCancel Cancels an asynchronous query Cancels an asynchronous query CreateParameterCreateParameterCreates a Parameter object for the Command Creates a Parameter object for the Command

object's Parameters collectionobject's Parameters collectionExecuteExecute Executes your queryExecutes your query

ADO Parameters CollectionADO Parameters CollectionMMethod Nameethod Name DescriptionDescriptionAppendAppend Appends a Parameter object to the Parameters Appends a Parameter object to the Parameters

collectioncollectionRefreshRefresh Refreshes the information for Parameter Refreshes the information for Parameter

object & collection, connected with currentobject & collection, connected with current command command

Page 35: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

ADO Parameter Object Properties and CollectionsADO Parameter Object Properties and Collectionsto enable you to reuse a query while changing a small piece of the query. For to enable you to reuse a query while changing a small piece of the query. For example, execute that query multiple times, changing only the value of the example, execute that query multiple times, changing only the value of the CustomerID each time the query is executed:CustomerID each time the query is executed:SELECT * FROM Customers WHERE CustomerID = ?SELECT * FROM Customers WHERE CustomerID = ?

Prop.or Coll. Name Prop.or Coll. Name Data Type Data Type DescriptionDescriptionDirectionDirection ParameterDirectionEnum Indicates which type of parameter ParameterDirectionEnum Indicates which type of parameter

you're using—input, output, you're using—input, output, input/output, or returninput/output, or return

NameName StringString Contains the name of the Parameter Contains the name of the Parameter objectobject

SizeSize LongLong Returns the defined size for a fieldReturns the defined size for a fieldTypeType DataTypeEnumDataTypeEnum Returns the data type for a fieldReturns the data type for a fieldValueValue VariantVariant the current value for a fieldthe current value for a field

ADO Parameter Object MethodADO Parameter Object MethodMethod NameMethod Name DescriptionDescriptionAppendChunkAppendChunk Adds chunks of string or binary data to the Parameter objectAdds chunks of string or binary data to the Parameter object

Page 36: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

The ADO Record and Stream ObjectsThe ADO Record and Stream ObjectsWhich OLE DB Providers Support the ADO Record Object?Which OLE DB Providers Support the ADO Record Object?

• OLE DB Provider For Internet Publishing• Microsoft Internet Explorer 5 ships with an OLE DB provider designed to

communicate with web servers -IIS 5. There's a growing standard among web servers called Web Distributed Authoring and Versioning (WebDAV), which defines a method of interaction with the files maintained by the web server. This standard set of interfaces allows web development tools such as Microsoft FrontPage to post new or modified files to your web site.

• The OLE DB Provider For Internet Publishing lets you use WebDAV to communicate with your web site by using ADO.

• OLE DB Provider For Microsoft Exchange Server• The Record and Stream objects are designed to make working with

"document" data stores (such as file systems and message stores). You could use such a provider to communicate with your mail server by using ADO to build e-mail applications like Microsoft Outlook.

Page 37: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

ADO Record ObjectADO Record ObjectOLE DB providers for traditional relational databases don't support OLE DB providers for traditional relational databases don't support Record object Record object

Hierarchical DataHierarchical DataFile systems, for example, contain files and directories. File systems, for example, contain files and directories. While a file might resemble a row in a table in a traditional relational database, a directory While a file might resemble a row in a table in a traditional relational database, a directory resembles both a row in a table and a table. resembles both a row in a table and a table. Call a Record object's Call a Record object's GetChildrenGetChildren method, and you'll receive a Recordset object that method, and you'll receive a Recordset object that contains the child data (the records) associated with that Record object.contains the child data (the records) associated with that Record object.

• Nonrectangular Data• Take data in a directory as an example. Files and subdirectories

have some of the same attributes, such as the name and the date created, but they also expose unique attributes. For example, files generally have an application associated with them, and directories generally contain information about whether they're visible as a network share. Because this structure of files and subdirectories within a directory exposes different attributes, the attribute data is considered nonrectangular.

• With Recordset object, you'd see only the common attributes (columns of data) that are exposed by both the files and subdirectories. Examining a file and a subdirectory as individual Record objects will expose all the attributes of both structures

Page 38: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO
Page 39: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

ADO Record Object Functions and MethodsADO Record Object Functions and Methods

Func or Method NameFunc or Method Name DescriptionDescription

CancelCancel Cancels an asynchronous action on the Record objectCancels an asynchronous action on the Record objectCloseClose Closes an open Record objectCloses an open Record objectCopyRecordCopyRecord Copies the Record object to another locationCopies the Record object to another locationDeleteRecordDeleteRecord Deletes the Record objectDeletes the Record objectGetChildrenGetChildren Retrieves the child data associated with the Record objectRetrieves the child data associated with the Record objectMoveRecordMoveRecord Moves the Record object to another locationMoves the Record object to another locationOpenOpen Opens an existing Record object or creates a new Record Opens an existing Record object or creates a new Record

objectobject

Page 40: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

ADO Recorset object Properties & collectionsADO Recorset object Properties & collections

ActiveConnectionActiveConnection

FieldsFields

ModeMode specify permissions for modification specify permissions for modification

of Record objectof Record object

ParentURLParentURL parent of the Record objectparent of the Record object

PropertiesProperties collection of dynamic propertiescollection of dynamic properties

SourceSource

Page 41: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

ADO Stream ObjectADO Stream ObjectUse Stream object in conjunction with the Record object to access document-Use Stream object in conjunction with the Record object to access document-based data.based data.Working with Document DataWorking with Document DataWhile the Record object allows you to interact with the structure of documents, While the Record object allows you to interact with the structure of documents, the Stream object lets you access the contents of those documents. the Stream object lets you access the contents of those documents. Stream.Open Record, adModeReadWrite, adOpenStreamFromRecordStream.Open Record, adModeReadWrite, adOpenStreamFromRecordStream.Position = 0Stream.Position = 0Stream.LoadFromFile strPathToFileStream.LoadFromFile strPathToFileStream.FlushStream.FlushAADO Stream Object Functions and MethodsDO Stream Object Functions and MethodsFunc or Method NameFunc or Method Name DescriptionDescriptionCancelCancel Cancels a pending asynchronous call to a Stream objectCancels a pending asynchronous call to a Stream objectCloseClose Closes an open Stream objectCloses an open Stream objectFlushFlush Flushes the contents stored in the Stream object's bufferFlushes the contents stored in the Stream object's bufferLoadFromFileLoadFromFile Loads the contents of a file into the streamLoads the contents of a file into the streamOpenOpen Opens the Stream objectOpens the Stream objectReadRead Reads binary data from the streamReads binary data from the streamSaveToFileSaveToFile Persist dataPersist dataWriteWrite Append data to the streamAppend data to the streamOpen MethodOpen MethodThe Open method opens a Stream Object from a Record object or URLThe Open method opens a Stream Object from a Record object or URL

Page 42: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

CursorsCursorsForward-Only CursorsForward-Only Cursors

The adOpenForwardOnly constant, a CursorTypeEnum type, corresponds The adOpenForwardOnly constant, a CursorTypeEnum type, corresponds to this type of cursor. It is the default value for a Recordset object's to this type of cursor. It is the default value for a Recordset object's CursorType property when you use the default value (adUseServer) for the CursorType property when you use the default value (adUseServer) for the Recordset object's CursorLocation property. ADO retrieves from the cursor Recordset object's CursorLocation property. ADO retrieves from the cursor up to the number of records specified by the CacheSize property in a up to the number of records specified by the CacheSize property in a Variant array, and then when you navigate beyond the data in the cache, Variant array, and then when you navigate beyond the data in the cache, ADO retrieves the next set of records ADO retrieves the next set of records

Page 43: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Firehose CursorsFirehose Cursorsforward-only, read-only, and one record at a time.forward-only, read-only, and one record at a time.No cursor like structure to store results.No cursor like structure to store results.Microsoft SQL Server is optimized for this type of query.Microsoft SQL Server is optimized for this type of query. SQL Server can support only one active query on a connection. If you open SQL Server can support only one active query on a connection. If you open a firehose cursor and do not fetch all of the data, and then close that cursor, a firehose cursor and do not fetch all of the data, and then close that cursor, you've tied up that connection. you've tied up that connection. OLE DB—the technology on which ADO is based— provider will simply OLE DB—the technology on which ADO is based— provider will simply request another connection. See three separate connections to your SQL request another connection. See three separate connections to your SQL Server database:Server database:Set cnNorthwind = New ADODB.ConnectionSet cnNorthwind = New ADODB.ConnectioncnNorthwind.CursorLocation = adUseServercnNorthwind.CursorLocation = adUseServercnNorthwind.Open strConncnNorthwind.Open strConnSet rsCustomers = cnNorthwind.Execute("SELECT * FROM Customers")Set rsCustomers = cnNorthwind.Execute("SELECT * FROM Customers")Set rsOrders = cnNorthwind.Execute("SELECT * FROM Orders")Set rsOrders = cnNorthwind.Execute("SELECT * FROM Orders")Set rsProducts = cnNorthwind.Execute("SELECT * FROM Products")Set rsProducts = cnNorthwind.Execute("SELECT * FROM Products")

/Adding New ADODB.Recordset before rs.Open” SQLstring” for the/Adding New ADODB.Recordset before rs.Open” SQLstring” for thecode above, results in constructing 3 separate static cursors /code above, results in constructing 3 separate static cursors /

Page 44: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Static CursorsStatic Cursorssupports scrolling forward supports scrolling forward andand backward. As the cursor name implies, backward. As the cursor name implies, the data is staticthe data is static

Static cursors are traditionally defined as read-only

Page 45: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Keyset CursorsKeyset CursorsNot only does a keyset cursor allow you to update data, but it also Not only does a keyset cursor allow you to update data, but it also lets you see changes made by other users. lets you see changes made by other users.

You can open a keyset cursor as read-only or updatable. Although you can see changes made by another user after you've opened your keyset cursor, you can't see new records . The data in the keyset (remember that this is the set of key values, not the cursor itself) is static.Records deleted by other users will be removed from your keyset cursor the next time you refresh the cache. With a deleted record in a keyset cursor you will receive a run-time error if you're using the SQL Server ODBC driver but not if you're using the OLE DB provider.

Page 46: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Dynamic CursorsDynamic Cursors

Can contain records that other users have added since initially submitted the query

Page 47: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Client-Side CursorsClient-Side Cursorsa static cursor. a static cursor.

•you will not see changes made to the database by other users• OLEDB provider uses for results a firehose cursor* However, a client-side recordset can be updatable* this static cursor is maintained by the ADO Cursor Engine rather than by the database system. * ask ADO to update the database, by means of the Update or UpdateBatch method

Page 48: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Database-Specific Cursor ConsiderationsDatabase-Specific Cursor Considerations

Server-Side Cursors with SQL ServerServer-Side Cursors with SQL Server1."cursors are evil,"1."cursors are evil,"2. When you use a server-side cursor with the SQL Server OLE DB provider or 2. When you use a server-side cursor with the SQL Server OLE DB provider or ODBC driver, you're using a cursor that's maintained by SQL Server itself.ODBC driver, you're using a cursor that's maintained by SQL Server itself.3. It makes much more sense for your database system to do what it's designed to 3. It makes much more sense for your database system to do what it's designed to do—store your data and process queries—rather than expend its resources do—store your data and process queries—rather than expend its resources storing the results of your queriesstoring the results of your queries4. if you're using server-side cursors in your application, you need a live 4. if you're using server-side cursors in your application, you need a live connection to the databaseconnection to the database5. As you add more users, you add more connections to your database, and the 5. As you add more users, you add more connections to your database, and the same instance of SQL Server needs to maintain the cursors for each user.same instance of SQL Server needs to maintain the cursors for each user.6. server-side cursors in your ADO and SQL Server application is a bad idea.6. server-side cursors in your ADO and SQL Server application is a bad idea.

Page 49: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Server-Side Cursors with AccessServer-Side Cursors with Access

1. Both the Access OLE DB provider and the Access ODBC driver support 1. Both the Access OLE DB provider and the Access ODBC driver support server-side cursors.server-side cursors.2. The term "server" is a little misleading when it comes to server-side 2. The term "server" is a little misleading when it comes to server-side cursors in Access.cursors in Access.3. With SQL Server, the database server maintains the cursor With Access, 3. With SQL Server, the database server maintains the cursor With Access, the OLE DB provider and ODBC driver have to do a great deal more workthe OLE DB provider and ODBC driver have to do a great deal more work4. When using a client-side cursor with an Access database, you're 4. When using a client-side cursor with an Access database, you're essentially moving data from the Access cursor engine to the ADO Cursor essentially moving data from the Access cursor engine to the ADO Cursor Engine. The Jet 4.0 OLE DB Provider or ODBC driver processes the query, Engine. The Jet 4.0 OLE DB Provider or ODBC driver processes the query, generates the results, and then has to pass all of this data to the ADO Cursor generates the results, and then has to pass all of this data to the ADO Cursor Engine one record at a time.Engine one record at a time.5. So should you simply not use client-side cursors with Access databases? 5. So should you simply not use client-side cursors with Access databases? Not so fast. Some of ADO's functionality (persisting Recordsets to file, batch Not so fast. Some of ADO's functionality (persisting Recordsets to file, batch updating, sorting Recordsets..) is available only with client-side Recordsets. updating, sorting Recordsets..) is available only with client-side Recordsets. Plus, if you're using a keyset or dynamic cursor to store the results of your Plus, if you're using a keyset or dynamic cursor to store the results of your Access queries, the OLE DB provider or ODBC driver still needs to examine Access queries, the OLE DB provider or ODBC driver still needs to examine the database every time the database every time

Page 50: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Server-Side Cursors with OracleServer-Side Cursors with Oracle

1. there are no OLE DB providers or ODBC drivers for Oracle that 1. there are no OLE DB providers or ODBC drivers for Oracle that support cursors outside stored procedures yet.support cursors outside stored procedures yet.2. Microsoft ODBC driver for Oracle has always supported cursors. 2. Microsoft ODBC driver for Oracle has always supported cursors. You can get a keyset cursor with the Microsoft ODBC driver for You can get a keyset cursor with the Microsoft ODBC driver for Oracle. How is this possible?The Microsoft ODBC driver for Oracle Oracle. How is this possible?The Microsoft ODBC driver for Oracle actually implements the cursor in a way that is somewhat similar to actually implements the cursor in a way that is somewhat similar to how the Access OLE DB provider and ODBC driver implement how the Access OLE DB provider and ODBC driver implement cursors. For a keyset cursor, the Microsoft ODBC driver for Oracle cursors. For a keyset cursor, the Microsoft ODBC driver for Oracle requests keyset information for the records that satisfy the query's requests keyset information for the records that satisfy the query's criteriacriteria3. less stress on the database server. The data in the cursor is 3. less stress on the database server. The data in the cursor is cached in the Microsoft ODBC driver for Oracle, and the Oracle cached in the Microsoft ODBC driver for Oracle, and the Oracle server does what it does best—it maintains data and processes server does what it does best—it maintains data and processes queries.queries.

Page 51: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Updating Your DatabaseUpdating Your Database1. Action Queries1. Action QueriesUPDATE Customers SET BalanceDue = 100 WHERE CustomerID = 7UPDATE Customers SET BalanceDue = 100 WHERE CustomerID = 7

It's easy to execute action queries using the ADO object modelIt's easy to execute action queries using the ADO object model(Execute method in Connection or Command objects):(Execute method in Connection or Command objects):Dim cnDatabase As ADODB.ConnectionDim cnDatabase As ADODB.ConnectionstrSQL = "UPDATE Customers SET BalanceDue =100 WHERE CustomerID=7“strSQL = "UPDATE Customers SET BalanceDue =100 WHERE CustomerID=7“cnDatabase.Execute strSQL, intRowsAffected, _cnDatabase.Execute strSQL, intRowsAffected, _                   adCmdExecuteNoRecords + adCmdText                   adCmdExecuteNoRecords + adCmdTextMsgBox intRowsAffected & " record(s) affected.“MsgBox intRowsAffected & " record(s) affected.“

pro&cons: flexibility, universal support, easy multi-user support, great deal of codepro&cons: flexibility, universal support, easy multi-user support, great deal of code

• 2. Stored Procedures• Many database administrators (DBAs) allow users to

perform updates only through stored procedures because of the level of control they offer.

Page 52: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

•SQL Server allows you to pass query results back from the stored procedure. SQL Server allows you to pass query results back from the stored procedure. Oracle doesn't. However, the Microsoft ODBC driver for Oracle and the OLE DB Provider For Oracle can Oracle doesn't. However, the Microsoft ODBC driver for Oracle and the OLE DB Provider For Oracle can retrieve an array from an Oracle stored procedure and transform that data into a structure that ADO will retrieve an array from an Oracle stored procedure and transform that data into a structure that ADO will use to create a Recordset object.use to create a Recordset object.* Stored procedures are faster than action queries. * Stored procedures are faster than action queries. * use stored procedures to isolate business rules from your application. * use stored procedures to isolate business rules from your application. * As a general rule, think of your stored procedure as a COM component.* As a general rule, think of your stored procedure as a COM component.* don’t move all your logic into stored procedures: hard migration in DB systems* don’t move all your logic into stored procedures: hard migration in DB systems

example of the ADO code required to call a stored procedure in SQL Server:example of the ADO code required to call a stored procedure in SQL Server:strSQL = "CALL SetBalanceDue('ALFKI', 150.00)“strSQL = "CALL SetBalanceDue('ALFKI', 150.00)“cnDatabase.Execute strSQL, , adCmdText + adExecuteNoRecordscnDatabase.Execute strSQL, , adCmdText + adExecuteNoRecords

And here's the SQL Server stored procedure that was called from the ADO code:And here's the SQL Server stored procedure that was called from the ADO code:CREATE PROCEDURE SetBalanceDueCREATE PROCEDURE SetBalanceDue(@CustomerID varchar(5), @BalanceDue money) AS(@CustomerID varchar(5), @BalanceDue money) ASUPDATE Customers SET BalanceDue = @BalanceDueUPDATE Customers SET BalanceDue = @BalanceDue                 WHERE CustomerID = @CustomerID                 WHERE CustomerID = @CustomerIDif two users retrieve the same customer's balance due, each user's update will succeed. This if two users retrieve the same customer's balance due, each user's update will succeed. This isn't a desirable scenario. The following is a better choice: isn't a desirable scenario. The following is a better choice:CREATE PROCEDURE SetBalanceDueCREATE PROCEDURE SetBalanceDue(@CustomerID varchar(5), @Delta money) AS(@CustomerID varchar(5), @Delta money) ASUPDATE Customers SET BalanceDue = BalanceDue + @DeltaUPDATE Customers SET BalanceDue = BalanceDue + @Delta                 WHERE CustomerID = @CustomerID                 WHERE CustomerID = @CustomerID

pros&cons: flexibility, faster than action queries, security, modification outside the pros&cons: flexibility, faster than action queries, security, modification outside the application, //specific to server, another prog. languageapplication, //specific to server, another prog. language

Page 53: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

33. Using Updatable Recordsets. Using Updatable RecordsetsUsed properly, updatable Recordsets can save you more time than Used properly, updatable Recordsets can save you more time than anything sold in an infomercial. anything sold in an infomercial. strSQL = "SELECT * FROM Customers“strSQL = "SELECT * FROM Customers“Set rsCustomers = New ADODB.RecordsetSet rsCustomers = New ADODB.RecordsetrsCustomers.Open strSQL, cnDatabase, adOpenKeyset, _ rsCustomers.Open strSQL, cnDatabase, adOpenKeyset, _                 adLockOptimistic, adCmdText                adLockOptimistic, adCmdTextrsCustomers("BalanceDue").Value = rsCustomers("BalanceDue").Value + 50rsCustomers("BalanceDue").Value = rsCustomers("BalanceDue").Value + 50rsCustomers.UpdatersCustomers.Update

• Updatable Server-Side Recordsets

• When you modify the Value property of the various Field objects in your Recordset and then call the Recordset's Update method, ADO passes that information to the server-side cursor through the OLE DB provider or ODBC driver. But who updates the database? Whoever manages the cursor.

• SQL Server actually manages the cursor. SQL Server also updates data in your database as you modify the contents of the cursor.

• Access OLE DB provider and ODBC driver manage the cursor & directly communicate with database.

• MS ODBC driver for Oracle manage the cursor.(Someday OLE DB provider will exist to do the same) After changes in cursor, ODBC driver tells the Oracle DB server to make modifications in the DB.

Page 54: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

disadvantages of updating your database by using server-side Recordsets:disadvantages of updating your database by using server-side Recordsets:

1. Server-side Recordsets require a live connection to your database. 1. Server-side Recordsets require a live connection to your database. 2. Server-side Recordsets sometimes scale poorly in multiuser situations.2. Server-side Recordsets sometimes scale poorly in multiuser situations.3. Because server-side Recordsets rely on the database system, the OLE DB provider, 3. Because server-side Recordsets rely on the database system, the OLE DB provider, or the ODBC driver to actually update the database, you might need to develop code or the ODBC driver to actually update the database, you might need to develop code that is specific to the type of database you're using. For example, Microsoft Access and that is specific to the type of database you're using. For example, Microsoft Access and SQL Server do not handle optimistic updates from live cursors the same way. SQL Server do not handle optimistic updates from live cursors the same way.

• Updatable Client-Side Recordsets• Functionality between action queries & server side Recordsets.• They behave the same way as server-side Recordsets. However, instead of communicating with a

cursor that’s maintained by the database, OLEDB provider or ODBC driver, ADO retrieves the results of your query and stores that data in its own Cursor Engine.

• The data in your Recordset is static• The ADO Cursor Engine examines the changes you make to the Recordset and translates those

changes into action queries. Cursor Engine determines whether the action query successfully updated the data in your database.

There's only one drawback to using client-side Recordsets . By allowing the ADO Cursor Engine to maintain the results of your queries and update your database, you still give up some control.

Page 55: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Comparison of ADO.NET and ADOComparison of ADO.NET and ADO

• In-memory Representations of Data

• In ADO, the in-memory representation of data is the recordset. In ADO.NET, it is the dataset. There are important differences between them.

• Number of Tables• A recordset looks like a single table. If a recordset is to contain data

from multiple database tables, it must use a JOIN query, which assembles the data from the various database tables into a single result table.

• In contrast, a dataset is a collection of one or more tables. The tables within a dataset are called data tables; specifically, they are DataTable objects. If a dataset contains data from multiple database tables, it will typically contain multiple DataTable objects.

• A dataset usually also contains relationships. A relationship within a dataset is analogous to a foreign-key relationship in a database

Page 56: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Data Navigation and CursorsData Navigation and CursorsIn ADO you scan sequentially through the rows of the recordset using the ADO In ADO you scan sequentially through the rows of the recordset using the ADO MoveNext method. In ADO.NET, rows are represented as collections, so you can MoveNext method. In ADO.NET, rows are represented as collections, so you can loop through a table as you would through any collection, or access particular loop through a table as you would through any collection, or access particular rows via ordinal or primary key index. DataRelation objects maintain information rows via ordinal or primary key index. DataRelation objects maintain information about master and detail records and provide a method that allows you to get about master and detail records and provide a method that allows you to get records related to the one you are working with. records related to the one you are working with. A A cursorcursor is a database element that controls record navigation, the ability to is a database element that controls record navigation, the ability to update data, and the visibility of changes made to the database by other users. update data, and the visibility of changes made to the database by other users. ADO.NET does not have an inherent cursor object, but instead includes data ADO.NET does not have an inherent cursor object, but instead includes data classes that provide the functionality of a traditional cursor. For example, the classes that provide the functionality of a traditional cursor. For example, the functionality of a forward-only, read-only cursor is available in the ADO.NET functionality of a forward-only, read-only cursor is available in the ADO.NET DataReader object. DataReader object. Minimized Open ConnectionsMinimized Open ConnectionsIn ADO.NET you open connections only long enough to perform a database In ADO.NET you open connections only long enough to perform a database operation, such as a Select or Update. You can read rows into a dataset and then operation, such as a Select or Update. You can read rows into a dataset and then work with them without staying connected to the data source. In ADO the work with them without staying connected to the data source. In ADO the recordset can provide disconnected access, but ADO is designed primarily for recordset can provide disconnected access, but ADO is designed primarily for connected access.connected access.There is one significant difference between disconnected processing in ADO and There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you communicate with the database by making calls to an OLE ADO.NET. In ADO you communicate with the database by making calls to an OLE DB provider. In ADO.NET you communicate with the database through a data DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter or SqlDataAdapter object), adapter (an OleDbDataAdapter or SqlDataAdapter object),

Page 57: Програмиране с А DO Общ преглед на  ADO   обектния модел книга  Programming ADO

Sharing Data Between ApplicationsSharing Data Between ApplicationsTo transmit an ADO disconnected recordset from one component to another, you To transmit an ADO disconnected recordset from one component to another, you use COM marshalling. To transmit data in ADO.NET, you use a dataset, which can use COM marshalling. To transmit data in ADO.NET, you use a dataset, which can transmit an XML stream.transmit an XML stream.The transmission of XML files offers the following advantages over COM The transmission of XML files offers the following advantages over COM marshalling:marshalling:Richer data typesRicher data typesCOM marshalling provides a limited set of data types — those defined by the COM COM marshalling provides a limited set of data types — those defined by the COM standard. Because the transmission of datasets in ADO.NET is based on an XML standard. Because the transmission of datasets in ADO.NET is based on an XML format, there is no restriction on data types. format, there is no restriction on data types. PerformancePerformanceTransmitting a large ADO recordset or a large ADO.NET dataset can consume Transmitting a large ADO recordset or a large ADO.NET dataset can consume network resources. ADO.NET offers performance advantage, in that ADO.NET network resources. ADO.NET offers performance advantage, in that ADO.NET does not require data-type conversions. ADO, which requires COM marshalling to does not require data-type conversions. ADO, which requires COM marshalling to transmit records sets among components, does require that ADO data types be transmit records sets among components, does require that ADO data types be converted to COM data types.converted to COM data types.Penetrating FirewallsPenetrating FirewallsA firewall can interfere with two components trying to transmit disconnected ADO A firewall can interfere with two components trying to transmit disconnected ADO recordsets. Remember, firewalls are typically configured to allow HTML text to recordsets. Remember, firewalls are typically configured to allow HTML text to pass, but to prevent system-level requests (such as COM marshalling) from pass, but to prevent system-level requests (such as COM marshalling) from passing.passing.Because components exchange ADO.NET datasets using XML, firewalls can allow Because components exchange ADO.NET datasets using XML, firewalls can allow datasets to pass.datasets to pass.