ADO Lecture

download ADO Lecture

of 57

Transcript of ADO Lecture

  • 8/2/2019 ADO Lecture

    1/57

    DODO

    ADOADO Programming ADOProgramming ADO

  • 8/2/2019 ADO Lecture

    2/57

    Connection Object Openand Closemethods

    ADO has no collection object in its object model containing all of the Connectionobjects. BeginTrans, CommitTrans, and RollbackTrans OpenSchemamethod 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 theConnection object.

    Executemethod to submit queries, including queries that generate Recordsets. Executemethod 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 checkthe 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 Executemethod.

    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.

  • 8/2/2019 ADO Lecture

    3/57

    RecordsetRecordset ObjectObject

    ** contains the results of your query.contains the results of your query.

    * Each column is stored in a Field object in the* Each column is stored in a Field object in the Recordset'sRecordset's Fields collection.Fields collection.* Open* Openmethod of themethod of the RecordsetRecordset object retrieve the results of a query either through theobject 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* You can also generate a RecordsetRecordset object by calling theobject by calling the ExecuteExecutemethod on either themethod on either the

    Connection or Command object.Connection or Command object.

    * The* The Recordset'sRecordset's ActiveConnectionActiveConnection property refers to the Connection object that theproperty refers to the Connection object that the

    RecordsetRecordset uses to communicate with the database.uses to communicate with the database.

    ** ActiveCommandActiveCommand property refers to the Command object that generated theproperty refers to the Command object that generated the RecordsetRecordset

    Dynamic Properties

    ADO's Properties collection contains Property objects that storeinformation 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 orintegrated security. ODBC API calls to take advantage of the uniquefeatures of your particular database system. ADO Properties collection isreserved for provider-specific features.

  • 8/2/2019 ADO Lecture

    4/57

    Obtaining aObtaining a RecordsetRecordset Without a Command ObjectWithout a Command Object

    If you are not going to execute your query more than once, youIf 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:

    strConnstrConn == "Provider=SQLOLEDB;Data"Provider=SQLOLEDB;Data Source=Source=MyServerMyServer;";" &&__

    "Initial"Initial Catalog=Catalog=NorthwindNorthwind;";" &&__

    "User"User ID=ID=MyUserIDMyUserID;Password=;Password=MyPasswordMyPassword;;

    SetSet cnNorthwindcnNorthwind == NewNew ADODB.ConnectionADODB.Connection

    cnNorthwindcnNorthwind.Open.Open strConnstrConn

    strSQLstrSQL == "SELECT"SELECT ** FROMFROM CustomersCustomers

    SetSet rsCustomersrsCustomers == NewNew ADODB.ADODB.RecordsetRecordset

    rsCustomersrsCustomers.Open.Open strSQLstrSQL,, cnNorthwindcnNorthwind

  • 8/2/2019 ADO Lecture

    5/57

    Connection Object: To Use or Not to UseConnection Object: To Use or Not to Use

    You might find that sometimes the only reason you use your ConneYou might find that sometimes the only reason you use your Connection objectction object

    is to openis to open RecordsetRecordset objects.objects.

    strConn = "Provider= SQLOLEDB;Data Source=MyServer;" & _

    "Initial Catalog=Northwind;" & _

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

    ActiveConnection parameter

  • 8/2/2019 ADO Lecture

    6/57

    But proceed with caution! do you want theBut proceed with caution! do you want the ActiveConnectionActiveConnection property on eachproperty on eachof yourof your RecordsetRecordset objects to refer to the same Connection object?objects to refer to the same Connection object?

    SetSet rsCustomersrsCustomers == NewNew ADODB.ADODB.RecordsetRecordset

    rsCustomersrsCustomers.Open.Open "SELECT"SELECT ** FROMFROM Customers",Customers", strConnstrConn

    SetSet rsOrdersrsOrders == NewNew ADODB.ADODB.RecordsetRecordsetrsOrdersrsOrders.Open.Open "SELECT"SELECT ** FROMFROM Orders",Orders", strConnstrConn

    each Recordset object was opened using the sameconnection string to communicate with the samedatabase;

    separate Connection object for each Recordset.

    Each Connection objects maintains its own physicalconnection to the database.

  • 8/2/2019 ADO Lecture

    7/57

    1.1. explicitly create a Connection object and use it with bothexplicitly create a Connection object and use it with bothRecordsetRecordsetobjects:objects:

    SetSet cnNorthwindcnNorthwind == NewNew ADODB.ConnectionADODB.Connection

    cnNorthwindcnNorthwind.Open.Open strConnstrConnSetSet rsCustomersrsCustomers == NewNew ADODB.ADODB.RecordsetRecordset

    rsCustomersrsCustomers.Open.Open "SELECT"SELECT ** FROMFROM Customers",Customers", cnNorthwindcnNorthwind

    SetSet rsOrdersrsOrders == NewNew ADODB.ADODB.RecordsetRecordset

    rsOrdersrsOrders.Open.Open "SELECT"SELECT ** FROMFROM Orders",Orders", cnNorthwincnNorthwin

    2.2. one Connection object,( without having to explicitly create one)one Connection object,( without having to explicitly create one) usingusing

    ActiveConnectionActiveConnectionproperty on the initialproperty on the initialRecordsetRecordsetobject for both of them:object for both of them:

    SetSet rsCustomersrsCustomers == NewNew ADODB.ADODB.RecordsetRecordset

    rsCustomersrsCustomers.Open.Open "SELECT"SELECT ** FROMFROM Customers",Customers", strConnSetstrConnSet

    rsOrdersrsOrders == NewNew ADODB.ADODB.RecordsetRecordsetrsOrdersrsOrders.Open.Open "SELECT"SELECT ** FROMFROM Orders",Orders",__

    rsCustomersrsCustomers..ActiveConnectionActiveConnection

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

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

  • 8/2/2019 ADO Lecture

    8/57

    Obtaining aObtaining a RecordsetRecordset Without a DatabaseWithout a Database

    1.1. Microsoft developed the ODBC cursor library.Microsoft developed the ODBC cursor library.

    2. Microsoft Visual Basic 5 users could retrieve the results of2. Microsoft Visual Basic 5 users could retrieve the results of a query into thisa query into this

    library and actually disconnect from the database and later reclibrary and actually disconnect from the database and later reconnect to theironnect to their

    databases to update.databases to update.

    3. Remote Data Services (RDS), provided early versions of ADO wi3. Remote Data Services (RDS), provided early versions of ADO with a cursorth a cursor

    engine. This technology allowed ADO to pass aengine. This technology allowed ADO to pass a

    recordsetrecordset

    across processacross process

    boundaries.boundaries.

    4. Beginning with ADO 2.0,4. Beginning with ADO 2.0, recordsetsrecordsets can be persisted to a file and reopenedcan be persisted to a file and reopened

    later.later.

    5. You can also create your own5. You can also create your own recordsetrecordset by taking aby taking a RecordsetRecordset objectobject

    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 reopenthe connection when you want to communicate with your databaseagain.Use ActiveConnection property of the Recordset object :

  • 8/2/2019 ADO Lecture

    9/57

    'Open'Open aa connectionconnection toto youryour database.database.

    SetSet cnDatabasecnDatabase == NewNew ADODB.ConnectionADODB.Connection

    cnDatabasecnDatabase..CursorLocationCursorLocation == adUseClientadUseClient

    cnDatabasecnDatabase.Open.Open strConnstrConn,, strUserIDstrUserID,, strPasswordstrPassword

    'Make'Make thethe queryquery andand retrieveretrieve thethe results.results.

    SetSet rsDatarsData == NewNew ADODB.ADODB.RecordsetRecordset

    rsDatarsData.Open.Open strSQLstrSQL,, cnDatabasecnDatabase,, adOpenStaticadOpenStatic,,__

    adLockBatchOptimisticadLockBatchOptimistic,, adCmdTextSetadCmdTextSetrsDatarsData..ActiveConnectionActiveConnection==NothingNothing

    'Close'Close youryour connectionconnection..

    cnDatabasecnDatabase.Close.Close

    'Modify'Modify youryour recordsetrecordset..

    'Reopen'Reopen youryour connection.connection.

    cnDatabasecnDatabase.Open.Open

    'Point'Point youryour recordsetrecordset atat youryour connection.connection.

    SetSet rsDatarsData..ActiveConnectionActiveConnection == cnDatabasecnDatabase

    'Submit'Submit thethe changeschanges fromfrom thethe recordsetrecordset toto youryour database.database.

    rsDatarsData..UpdateBatchUpdateBatch

  • 8/2/2019 ADO Lecture

    10/57

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

    reconnect to the database Openmethod of the Connectionobject,

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

  • 8/2/2019 ADO Lecture

    11/57

    Persistence Can Pay OffPersistence Can Pay Off

    ADO 2.0 introduced functionality that makes it possible to storeADO 2.0 introduced functionality that makes it possible to store database information ondatabase information onthe desktop without having a desktop database. ADOthe desktop without having a desktop database. ADO RecordsetRecordset object has aobject has a SaveSave

    methodmethod

    'Retrieve'Retrieve thethe resultsresults ofof youryour queryquery andand savesave themthem toto aa file.file. TheThe pathpath toto thethe filefile

    '' andand thethe filenamefilename areare storedstored inin thethe stringstring strPathToOrdersFilestrPathToOrdersFile..

    SetSet cnDatabasecnDatabase == NewNew ADODB.ConnectionADODB.ConnectionSetSet rsOrdersrsOrders == NewNew ADODB.ADODB.RecordsetRecordset

    rsOrdersrsOrders.Open.Open strSQLstrSQL,, cnDatabasecnDatabase,, adOpenStaticadOpenStatic,,__

    adLockBatchOptimisticadLockBatchOptimistic,, adCmdTextadCmdText

    rsOrdersrsOrders.Save.Save strPathToOrdersFilestrPathToOrdersFile

    'Retrieve'Retrieve thethe contentscontents ofof thethe filefile intointo aa RecordsetRecordset,,

    '' modifymodify thethe RecordsetRecordset accordingly,accordingly, andand thenthen savesave thethe changeschanges backback toto aa file.file.

    rsOrdersrsOrders.Open.Open strPathToOrdersFilestrPathToOrdersFile,, ,, ,,__

    adLockBatchOptimisticadLockBatchOptimistic,, adCmdFileadCmdFile

    rsOrdersrsOrders..AddNewAddNew

    rsOrdersrsOrders.Update.Update

    rsOrdersrsOrders.Save.Save strPathToOrdersFilestrPathToOrdersFile

    'Retrieve'Retrieve thethe contentscontents ofof thethe filefile intointo aa RecordsetRecordset && submitsubmit thethe changeschanges toto youryour databasedatabase..

    rsOrdersrsOrders.Open.Open strPathToOrdersFilestrPathToOrdersFile,, ,, ,,__

    adLockBatchOptimisticadLockBatchOptimistic,, adCmdFileadCmdFile

    SetSet rsOrdersrsOrders..ActiveConnectionActiveConnection == cnDatabasecnDatabasersOrdersrsOrders..UpdateBatchUpdateBatch

  • 8/2/2019 ADO Lecture

    12/57

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

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

    after CommitTransor RollbackTranshas been calledCommandTimeout Long Sets the length of time that queries on this

    connection can run before timing outConnectionString String Specifies how to connect to your databaseConnectionTimeout Long Sets the length of time that ADO will wait before

    an attempt to connect to your db times outCursorLocation Long Sets the default value for the location of the cursorfor Recordsets opened on this Connection object

    DefaultDatabase String When connecting to Microsoft SQL Server andother database servers that expose multipledatabases, specifies which database to use

    Errors Collection of Error objects Each Error object contains information

    about an error that occurred on the Connection objectIsolationLevel Long Controls the level at which transactions for thedatabase are isolated

    Mode Long Sets the permissions for modification of the ConnectionobjectProperties 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 objectVersion String Version of ADO

  • 8/2/2019 ADO Lecture

    13/57

    IsolationLevelIsolationLevel PropertyPropertyYou can use theYou can use the IsolationLevelIsolationLevel property to control the isolation level of theproperty to control the isolation level of the

    transactions on your Connection object. The property can be settransactions on your Connection object. The property can be set to any one of theto any one of theIsolationLevelEnumIsolationLevelEnum values listed:values listed:

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

    isolation level that cannot be determinedadXactBrowse,

    adXactReadUncommitted 256 Allows you to view changes pending inanother transaction Subject to nonrepeatablereads and phantom rows

    adXactCursorStability,adXactReadCommitted 4096 Default; ensures that your transaction doesnot view any pending updates Subject tononrepeatable reads and phantom rows, butimmune to dirty reads

    adXactRepeatableRead 65536 Ensures that your transaction does not view

    any pending updates and that rows you readare not modified by other transactions Subjectto phantom rows

    adXactIsolated,

    adXactSerializable 1048576 Specifies complete isolation from other

    transactions

  • 8/2/2019 ADO Lecture

    14/57

    ADO Connection Object Functions and MethodsADO Connection Object Functions and Methods

    Connection Object Functions and Methods Function or MethodName Description

    BeginTrans Initiates a transactionCancel Cancels an asynchronous attempt to

    connect to your database

    Close Closes the connection to yourdatabaseCommitTrans 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

  • 8/2/2019 ADO Lecture

    15/57

    Connection.ExecuteConnection.ExecuteCommandTextCommandText,, RecordsAffectedRecordsAffected,, OptionsOptions

    cnDatabasecnDatabase.Execute.Execute"DELETE"DELETEFROMFROMMyTableMyTableWHEREWHEREIDID==77

    By default, theBy default, the ExecuteExecutemethod on the Connection object returns amethod on the Connection object returns a RecordsetRecordset

    object:object:

    'Create'Create aa newnew RecordsetRecordset..SetSet rsResultsrsResults == NewNew ADODB.ADODB.RecordsetRecordset

    'Set'Set thethe RecordsetRecordset toto useuse aa keysetkeyset cursorcursor andand optimisticoptimistic locking.locking.

    'These'These settingssettings makemake thethe RecordsetRecordset updatableupdatable

    ..rsResultsrsResults..CursorTypeCursorType == adOpenKeysetadOpenKeyset

    rsResultsrsResults..LockTypeLockType == adLockOptimisticadLockOptimistic'Call'Call Connection.ExecuteConnection.Execute andand retrieveretrieve aa new,new, nonupdatablenonupdatable RecordsetRecordset object.object.

    SetSet rsResultsrsResults == cnDatabasecnDatabase.Execute(.Execute(strSQLstrSQL))

    if you want to maintain any control over theif you want to maintain any control over the RecordsetRecordset object generated byobject generated by

    your query, use theyour query, use the OpenOpenmethod on themethod on the RecordsetRecordset object rather than theobject rather than theExecuteExecutemethod of the Connection object.method of the Connection object.

    The best use of theThe best use of the ExecuteExecutemethod is for action queriesmethod is for action queriesqueries that will notqueries that will not

    return areturn a recordsetrecordset

  • 8/2/2019 ADO Lecture

    16/57

    OpenOpenMethodMethod

    You use theYou use the OpenOpenmethod to connect to your database.method to connect to your database.

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

    OpenSchemaOpenSchemaMethodMethod

    provide a list of tables and the names of the fields in each tabprovide a list of tables and the names of the fields in each table. You might even want tole. You might even want toretrieve foreign key constraints to show relationships within thretrieve foreign key constraints to show relationships within the database. Thee database. The OpenSchemaOpenSchema

    method returns amethod returns a RecordsetRecordset object to help you retrieve this type of information:object to help you retrieve this type of information:

    SetSet RecordsetRecordset== ConnectionConnection..OpenSchemaOpenSchema QueryTypeQueryType,, CriteriaCriteria,, SchemaIDSchemaID

    The current documentation forThe current documentation for adSchemaColumnsadSchemaColumns lists four available restrictions:lists four available restrictions:

    TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, and COLUMN_NAME.:TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, and COLUMN_NAME.:

    DimDim rsSchemarsSchema AsAs ADODB.ADODB.RecordsetRecordset

    DimDim aRestrictionsaRestrictions AsAs VariantVariant

    aRestrictionsaRestrictions == Array(Empty,Array(Empty, Empty,Empty, "Customers","Customers", Empty)Empty)

    SetSet rsSchemarsSchema == cnDatabasecnDatabase..OpenSchemaOpenSchema((adSchemaColumnsadSchemaColumns,, aRestrictionsaRestrictions))

  • 8/2/2019 ADO Lecture

    17/57

    ADO Connection Object EventsADO Connection Object Events

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

    Connection Object EventsConnection Object Events

    Event NameEvent Name DescriptionDescription

    BeginTransCompleteBeginTransComplete Fires when theFires when the BeginTransBeginTransmethod completesmethod completesCommitTransCompleteCommitTransComplete Fires when theFires when the CommitTransCommitTransmethod completesmethod completes

    ConnectCompleteConnectComplete Fires when the attempt to connect completesFires when the attempt to connect completes

    DisconnectDisconnect Fires when theFires when the CloseClosemethod completesmethod completes

    ExecuteCompleteExecuteComplete Fires when theFires when the ExecuteExecutemethod completesmethod completes

    InfoMessageInfoMessage Returns informational error messagesReturns informational error messagesRollbackTransCompleteRollbackTransComplete Fires when theFires when the RollbackTransRollbackTransmethod completesmethod completes

    WillConnectWillConnect Fires when theFires when the OpenOpenmethod on the Connectionmethod on the Connection

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

    databasedatabase

    WillExecuteWillExecute Fires prior to submitting a query to the ConnectionFires prior to submitting a query to the Connection

    object with the Execute method or when the Openobject with the Execute method or when the Open

    method is called on amethod is called on a RecordsetRecordset associated with theassociated with the

    Connection objectConnection object

  • 8/2/2019 ADO Lecture

    18/57

    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 nativeOLE 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 ODBCfunctionality, you should still be able to use ADO. The OLE DB Provider For ODBC Drivers makes ODBC APIcalls 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 Databases

    communicate with Oracle's client components rather than directly with the Oracle database. In order to useADO 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;"

  • 8/2/2019 ADO Lecture

    19/57

    Managing Your TransactionsManaging Your Transactions

    BeginTransBeginTrans,, CommitTransCommitTrans, and, andRollbackTransRollbackTransMethodsMethods

    OnOnErrorErrorResumeResumeNextNext

    'Start'Startthethetransaction.transaction.

    cnDatabasecnDatabase..BeginTransBeginTrans

    strSQLstrSQL =="UPDATE"UPDATESavingsSavingsSETSETBalDueBalDue==BalDueBalDue--5050""&& "WHERE"WHEREAccountNumberAccountNumber==123456789123456789cnDatabasecnDatabase.Execute.ExecutestrSQLstrSQL

    IfIfcnDatabasecnDatabase.Errors.Count.Errors.Count>>00ThenThen

    'An'Anerrorerroroccurred,occurred, cancelcancelchanges.changes.

    cnDatabasecnDatabase..RollbackTransRollbackTrans

    ElseElse

    strSQLstrSQL =="UPDATE"UPDATECheckingCheckingSETSETBalDueBalDue==BalDueBalDue++5050""&& __WHEREWHEREAccountNumberAccountNumber==123456789"123456789"

    cnDatabasecnDatabase.Execute.ExecutestrSQLstrSQL

    IfIfcnDatabasecnDatabase.Errors.Count.Errors.Count>>00ThenThen

    'An'Anerrorerroroccurred,occurred, cancelcancelallallofofthethechanges.changes.

    cnDatabasecnDatabase..RollbackTransRollbackTransElseElse

    NoNoerrorserrorsoccurred,occurred, commitcommitallallofofthethechanges.changes.

    cnDatabasecnDatabase..CommitTransCommitTrans

    EndEndIfIf

    EndEndIfIf

  • 8/2/2019 ADO Lecture

    20/57

    IsolationLevelIsolationLevel PropertyProperty

    Definitions of Some Transactional Terms

    dirty read When one transaction reads uncommitted changesfrom another transaction.

    nonrepeatable read When data read in transaction A is modified bytransaction 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 criteriafor 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 appearmysteriously (like a phantom) in the second set of results.

    SQL Server supports all four isolation levels ( Read Committed - default). You canset 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 Yes

    Repeatable Read No No YesSerializable No No No

  • 8/2/2019 ADO Lecture

    21/57

    The ADOThe ADO RecordsetRecordset and Field Objectsand Field Objects

    ADOADO RecordsetRecordset Object Properties and CollectionsObject Properties and Collections

    Recordset Object Properties and Collections

    Property or Coll. Name Data Type Description

    ActiveCommand Variant Pointer to the Command object that created theRecordset object

    ActiveConnection String or Connection Connection object used to retrievethe 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 datasource

    Fields Collection of Field objects Pointer to the collection of Field objects thatcontain 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 returnedPageCount Long Returns the number of pages in your RecordsetPageSize Long number of records per page in your RecordsetRecordCount Long Returns the number of records in the RecordsetSort String Allows you to reorder the data in your Recordset

    Status RecordStatusEnum Returns the update status of the current record

  • 8/2/2019 ADO Lecture

    22/57

    Some Details about properties & collectionsSome Details about properties & collections

    CursorTypeCursorType PropertyProperty

    CursorTypeEnumCursorTypeEnum ValuesValues

    ConstantConstant

    ValueValue

    DescriptionDescription

    adOpenForwardOnlyadOpenForwardOnly 00 Default for serverDefault for server--sideside RecordsetsRecordsets; opens a; opens a

    RecordsetRecordset that supports scrolling forward onlythat supports scrolling forward only

    adOpenStaticadOpenStatic 33 Default and only possible value for clientDefault and only possible value for client--sideside

    RecordsetsRecordsets; supports scrolling forward and; supports scrolling forward and

    backward; changes made by other users arebackward; changes made by other users arenot visiblenot visible

    adOpenKeysetadOpenKeyset 11 Supports scrolling forward and backward;Supports scrolling forward and backward;

    modifications and deletions by other users aremodifications and deletions by other users are

    visiblevisible

    adOpenDynamicadOpenDynamic 22 Supports scrolling forward and backward;Supports scrolling forward and backward;modifications, deletions, and insertions mademodifications, deletions, and insertions made

    by other users are visibleby other users are visible

  • 8/2/2019 ADO Lecture

    23/57

    Fields CollectionFields Collection

    In the following Visual Basic code, all lines are equivalent toIn the following Visual Basic code, all lines are equivalent to each other,each other,

    referring to the Value property for thereferring to the Value property for the CustomerIDCustomerID field in thefield in the rsCustomersrsCustomers

    RecordsetRecordset object (assumingobject (assuming CustomerIDCustomerID is the first field in theis the first field in the RecordsetRecordset):):

    rsCustomersrsCustomers.Fields(".Fields("CustomerIDCustomerID").Value").Value

    rsCustomers.Fields(0).ValuersCustomers.Fields(0).Value

    rsCustomers(0).ValuersCustomers(0).Value

    rsCustomersrsCustomers("CustomerID").Value("CustomerID").Value

    rsCustomersrsCustomers.Fields(".Fields("CustomerIDCustomerID")")

    rsCustomers.Fields(0)rsCustomers.Fields(0)

    rsCustomers(0)rsCustomers(0)

    rsCustomersrsCustomers

    ("("

    CustomerIDCustomerID

    ")")

  • 8/2/2019 ADO Lecture

    24/57

    Filter PropertyFilter Property whichwhich records inrecords in RecordsetRecordset to viewto view

    you can set the property to a string or to a value inyou can set the property to a string or to a value in FilterGroupEnumFilterGroupEnum

    FilterGroupEnumFilterGroupEnum ValuesValues

    ConstantConstant ValueValue DescriptionDescription

    adFilterNoneadFilterNone 00 Default; clears the current filterDefault; clears the current filter

    adFilterPendingRecordsadFilterPendingRecords 11 Displays only the records withDisplays only the records with

    pending changespending changes

    adFilterAffectedRecordsadFilterAffectedRecords 22 Displays only the records affectedDisplays only the records affected

    by the last call toby the last call to DeleteDelete,, ResyncResync,,

    UpdateBatchUpdateBatch, or, or CancelBatchCancelBatch

    adFilterFetchedRecordsadFilterFetchedRecords 33 Displays only the records currentlyDisplays only the records currently

    stored in the cachestored in the cacheadFilterConflictingRecordsadFilterConflictingRecords 55 Displays only the records that failedDisplays 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

    rsOrdersrsOrders.Filter.Filter == ""CustomerIDCustomerID == 'ALFKI'"'ALFKI'"

    strCriteriastrCriteria==""CompanyNameCompanyName==''Trail''sTrail''sHeadHeadGourmet'Gourmet'

    rsCustomersrsCustomers.Filter.Filter==strCriteriastrCriteria

  • 8/2/2019 ADO Lecture

    25/57

    LockTypeLockType PropertyProperty

    LockTypeEnumLockTypeEnum ValuesValues

    ConstantConstant ValueValue DescriptionDescription

    adLockReadOnlyadLockReadOnly 11 Default; theDefault; the RecordsetRecordset is readis read--

    only.only.

    adLockPessimisticadLockPessimistic 22 ADO relies on the OLE DBADO relies on the OLE DBprovider to ensure that yourprovider to ensure that your

    update attempt will succeed.update attempt will succeed.

    Only 1 user/moment. LockedOnly 1 user/moment. Locked

    for others.for others.adLockOptimisticadLockOptimistic 33 The data is not locked until oneThe data is not locked until one

    callcall UpdateUpdate..

    adLockBatchOptimisticadLockBatchOptimistic 44 Modifications to your data areModifications to your data are

    cached until you callcached until you call

    UpdateBatchUpdateBatch

    .

    .

    Designed for client sideDesigned for client side RecordsetsRecordsets..

    Works with server side, if OLE DB provider supports the functionWorks with server side, if OLE DB provider supports the functionalityality

    (Access(Access not, SQL Servernot, SQL Server yes)yes)

  • 8/2/2019 ADO Lecture

    26/57

    ADOADO RecordsetRecordset Object MethodsObject Methods

    AddNewAddNew Adds a new record to yourAdds a new record to your RecordsetRecordset

    CancelCancel Cancels an asynchronous queryCancels an asynchronous queryCancelUpdateCancelUpdate Cancels pending changes on a record currentlyCancels pending changes on a record currently

    being editedbeing edited

    CloseClose Closes theCloses the RecordsetRecordset object, releasing its contentsobject, releasing its contents DeleteDelete

    Deletes the current record from yourDeletes the current record from your RecordsetRecordset

    FindFind Searches yourSearches your RecordsetRecordset for a recordsfor a recordsGetRowsGetRows Returns data from yourReturns data from your RecordsetRecordset in a twoin a two--

    dimensional Variant arraydimensional Variant array

    GetStringGetString Returns data from yourReturns data from your RecordsetRecordset in a stringin a string

    MoveMove Moves the position inMoves the position in RecordsetRecordset

    MoveFirstMoveFirst Moves to the first record in yourMoves to the first record in your RecordsetRecordset

    MoveLastMoveLast Moves to the last record in yourMoves to the last record in your RecordsetRecordset

    MoveNextMoveNext Moves to the next record in yourMoves to the next record in your RecordsetRecordset

    MovePreviousMovePrevious Moves to the previous record in yourMoves to the previous record in your RecordsetRecordset

    NextRecordsetNextRecordset Retrieves results of the next query (Retrieves results of the next query (RecordSetRecordSet)in batch query)in batch query

    OpenOpen Opens theOpens the RecordsetRecordset

    RequeryRequery ReexecutesReexecutes the query that generated thethe query that generated the RecordsetRecordsetSaveSave Writes the contents of theWrites the contents of the RecordsetRecordset to a fileto a file

    SeekSeek Searches theSearches the RecordsetRecordset for a specified stringfor a specified string

    UpdateUpdate Writes pending changes to theWrites pending changes to the RecordsetRecordset & DB& DB unless you areunless you areusing batch update (using batch update (LockTypeLockType == adLockBatchOptimisticadLockBatchOptimistic). In that case). In that case

    modifications only cashedmodifications only cashedUpdateBatchUpdateBatch fromfrom RecordSetRecordSet to DBto DB

  • 8/2/2019 ADO Lecture

    27/57

    Examples:Examples:

    rsCustomersrsCustomers..AddNewAddNew

    rsCustomersrsCustomers.Fields(".Fields("CustomerIDCustomerID").Value").Value==""NewIDNewIDrsCustomersrsCustomers.Fields(".Fields("CompanyNameCompanyName")")=="New"NewCustomerCustomer

    rsCustomersrsCustomers.Fields("Address").Value.Fields("Address").Value=="23"23HighviewHighviewSt.St.

    rsCustomersrsCustomers.Fields("City").Fields("City")=="Westwood"Westwood

    rsCustomersrsCustomers.Fields("State").Fields("State")=="MA"MA

    rsCustomersrsCustomers.Fields("Zip").Fields("Zip")=="02090"02090rsCustomersrsCustomers.Update.Update

    strCriteriastrCriteria=="Country"Country=='Germany''Germany'

    rsCustomersrsCustomers.Find.FindstrCriteriastrCriteria

    DoDoWhileWhileNotNotrsCustomersrsCustomers.EOF.EOFrsCustomersrsCustomers.Find.FindstrCriteriastrCriteria,, 11

    LoopLoop

    strSQLstrSQL =="SELECT"SELECT**FROMFROMCustomersCustomers

    rsCustomersrsCustomers.Open.OpenstrSQLstrSQL,, cnDatabasecnDatabase,, adOpenForwardOnlyadOpenForwardOnlyDoDoWhileWhileNotNotrsCustomersrsCustomers.EOF.EOF

    Debug.PrintDebug.PrintrsCustomersrsCustomers.Fields(".Fields("CustomerIDCustomerID").Value").Value

    rsCustomersrsCustomers..MoveNextMoveNext

    LoopLoop

  • 8/2/2019 ADO Lecture

    28/57

    OpenOpenMethodMethod

    TheThe OpenOpenmethod is the most powerful and versatile method of retrievingmethod is the most powerful and versatile method of retrieving datadata

    from your database. You can set thefrom your database. You can set the ActiveConnectionActiveConnection, Source,, Source, LockTypeLockType,,andand CursorTypeCursorType properties on theproperties on the RecordsetRecordset prior to using theprior to using the OpenOpenmethod,method,

    or you can supply this data in its parameters, all of which areor you can supply this data in its parameters, all of which are optional:optional:

    ** SourceSource This parameter accepts a Variant. You can use theThis parameter accepts a Variant. You can use the SourceSource

    parameter to specify the query string or Command objectparameter to specify the query string or Command objectyou want to use. This parameter can also contain a tableyou 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.

    ActiveConnectionActiveConnectionThis parameter accepts a Variant in the form of aThis parameter accepts a Variant in the form of a

    connection string or an open Connection object, just like theconnection string or an open Connection object, just like the

    ActiveConnectionActiveConnection property.property.CursorTypeCursorType laterlater

    LockTypeLockType

    OptionsOptions CommandTypeEnumCommandTypeEnum value and/or a combination ofvalue and/or a combination of

    asynchronousasynchronous ExecuteOptionEnumExecuteOptionEnum constantsconstants

    rsCustomersrsCustomers.Open.Open "Customers","Customers", cnNorthwindcnNorthwind, _, _

    adOpenStaticadOpenStatic,, adLockReadOnlyadLockReadOnly,, adCmdTableadCmdTable ++ adAsyncExecuteadAsyncExecute

  • 8/2/2019 ADO Lecture

    29/57

    ADOADO RecordsetRecordset Object EventsObject Events

    Event NameEvent Name DescriptionDescription

    EndOfRecordsetEndOfRecordset Fires when you navigate beyond the last record ofFires when you navigate beyond the last record ofdata in yourdata in your RecordsetRecordset

    FieldChangeCompleteFieldChangeComplete Fires after you've modified the value for a fieldFires after you've modified the value for a field

    MoveCompleteMoveComplete Fires after the current position of theFires after the current position of the RecordsetRecordset

    changeschanges

    RecordChangeCompleteRecordChangeCompleteFires after you modify a recordFires after you modify a recordRecordsetChangeCompleteRecordsetChangeCompleteFires after theFires after the RecordsetRecordset object has changedobject has changed

    WillChangeFieldWillChangeField Fires before the contents of a field changeFires before the contents of a field change

    WillChangeRecordWillChangeRecord Fires before the contents of a record changeFires before the contents of a record change

    WillChangeRecordsetWillChangeRecordset Fires before theFires before the RecordsetRecordset object changesobject changes

    WillMoveWillMove Fires before the current position in theFires before the current position in the RecordsetRecordsetchangeschanges

  • 8/2/2019 ADO Lecture

    30/57

    ADO Fields Collection forADO Fields Collection for RecordsetRecordset

    Like all collections, the Fields collection exposes aLike all collections, the Fields collection exposes a Count propertyCount property and anand an ItemItem

    property (the default). With the Item property, you can return aproperty (the default). With the Item property, you can return a particular Field byparticular Field by

    name or index.name or index.

    Method NameMethod Name DescriptionDescription

    AppendAppend Adds a new Field ( forAdds a new Field ( for RecordsetRecordset) to the collection (without DB)) to the collection (without DB)

    CancelUpdateCancelUpdate Cancels the pending changes for a recordCancels the pending changes for a record

    DeleteDelete Deletes a Field from the collectionDeletes a Field from the collectionRefreshRefresh Refreshes the Fields collectionRefreshes the Fields collection

    ResyncResync Resynchronizes the current recordResynchronizes the current record

    UpdateUpdate Submits the pending changes in a recordSubmits the pending changes in a record

    AppendAppendMethodMethod

    You can use theYou can use the AppendAppendmethod on the Fields collection to create your ownmethod on the Fields collection to create your ownRecordsetRecordset object without using a database. You can populate the Fields coobject without using a database. You can populate the Fields collectionllection

    with Field objects in this fashion and then call thewith Field objects in this fashion and then call the RecordsetRecordset.Open.Openmethod to startmethod to start

    adding records to youradding records to your RecordsetRecordset. If you're not trying to communicate with a. If you're not trying to communicate with a

    database but would like to maintain your data in adatabase but would like to maintain your data in a RecordsetRecordset object, this methodobject, this method

    is for you. Its parameters are as follows:is for you. Its parameters are as follows:NameName

    TypeType

    DefinedSizeDefinedSize

    AttributesAttributes

    FieldValueFieldValue

  • 8/2/2019 ADO Lecture

    31/57

    ADO Field Object PropertiesADO Field Object Properties

    Property NameProperty Name Data TypeData Type DescriptionDescription

    ActualSizeActualSize LongLong Returns the actual size of a field's valueReturns the actual size of a field's value

    AttributesAttributes LongLong Describes characteristics of the fieldDescribes characteristics of the fieldDataFormatDataFormat ObjectObject Can be used to format your dataCan be used to format your data

    DefinedSizeDefinedSize LongLong Returns the defined size for a fieldReturns the defined size for a field

    NameName StringString Contains the name of the fieldContains the name of the field

    NumericScaleNumericScale ByteByte Indicates the numeric scale for numeric dataIndicates the numeric scale for numeric data

    OriginalValueOriginalValue Variant Contains the original value for the fieldVariant Contains the original value for the field

    PrecisionPrecision ByteByte Indicates the precision for numeric dataIndicates the precision for numeric data

    PropertiesProperties Collection of Property objectsCollection of Property objects Collection of dynamicCollection of dynamic

    propertiesproperties

    TypeType

    ByteByte

    Returns the data type for the fieldReturns the data type for the field

    UnderlyingValueUnderlyingValue Variant Indicates the most recently retrieved valueVariant Indicates the most recently retrieved value

    from the database for the fieldfrom the database for the field

    ValueValue Variant Contains the current value for the fieldVariant Contains the current value for the field

  • 8/2/2019 ADO Lecture

    32/57

    ADO Field Object MethodsADO Field Object Methods

    Method NameMethod Name DescriptionDescription

    AppendChunkAppendChunk Appends data to a large string or binary fieldAppends data to a large string or binary fieldGetChunkGetChunk Retrieves data from a large string or binary fieldRetrieves 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 singleThis object's primary use is for repeated execution of a single query orquery or

    multiple similar queries. The Command object exposes a Parametermultiple similar queries. The Command object exposes a Parametersscollection, with each Parameter object corresponding to a paramecollection, with each Parameter object corresponding to a parameter in ater in a

    queryquery

    ADO Command Object Properties and CollectionsADO Command Object Properties and Collections

    Prop. or Coll. Name Data TypeProp. or Coll. Name Data Type DescriptionDescription

    ActiveConnectionActiveConnection String orString or ConnectionSpecifiesConnectionSpecifies the Connection objectthe Connection objectused to communicate with your databaseused to communicate with your database

    CommandTextCommandText StringString Contains the query string or the name of theContains the query string or the name of the

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

    executeexecute

    CommandTimeoutCommandTimeout LongLong Controls the number of seconds the queryControls the number of seconds the query

    will run before timing outwill run before timing out

    NameName StringString the name of the Command objectthe name of the Command object

    ParametersParameters Collection of Parameter objects Contains parameterCollection of Parameter objects Contains parameter

    information for the queryinformation for the query

  • 8/2/2019 ADO Lecture

    33/57

    CommandTypeCommandType PropertyProperty

    ConstantConstant ValueValue DescriptionDescription

    adCmdTextadCmdText 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 storedADO will format the query as a call to a stored

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

    WithWithcmdStoredProccmdStoredProc'Specify'SpecifythatthatthetheCommandCommandobjectobjectwillwillcallcallaastoredstoredprocedure.procedure.

    ..CommandTypeCommandType==adCmdStoredProcadCmdStoredProc

    'Specify'Specifythethestoredstoredprocedureprocedurename.name.

    ..CommandTextCommandText==""MySPMySP""

    ''CommandTextCommandTextpropertypropertynownowcontainscontains"{"{callcallMySPMySP}".}".'Populate'PopulatethetheParametersParameterscollection.collection.

    .Parameters.Append.Parameters.Append..CreateParameterCreateParameter("@("@RetValRetVal",", adIntegeradInteger,, __

    adParamReturnValueadParamReturnValue))

    .Parameters.Append.Parameters.Append.CreateParameter("@Param1",.CreateParameter("@Param1", adIntegeradInteger,, __

    adParamInputadParamInput)).Parameters.Append.Parameters.Append.CreateParameter("@Param2",.CreateParameter("@Param2", adIntegeradInteger,, __

    adParamInputadParamInput))

    ''CommandTextCommandTextpropertypropertynownowcontainscontains"{"{??==callcallMySPMySP(?,(?, ?)?)}".}".

    EndEndWithWith

    name

    In/out

  • 8/2/2019 ADO Lecture

    34/57

    ADO Command Object MethodsADO Command Object Methods

    Method NameMethod Name DescriptionDescription

    CancelCancel Cancels an asynchronous queryCancels an asynchronous query

    CreateParameterCreateParameter Creates a Parameter object for the CommandCreates a Parameter object for the Commandobject's Parameters collectionobject's Parameters collection

    ExecuteExecute Executes your queryExecutes your query

    ADO Parameters CollectionADO Parameters Collection

    MMethod Nameethod Name DescriptionDescriptionAppendAppend Appends a Parameter object to the ParametersAppends a Parameter object to the Parameters

    collectioncollection

    RefreshRefresh Refreshes the information for ParameterRefreshes the information for Parameter

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

    commandcommand

  • 8/2/2019 ADO Lecture

    35/57

    ADO Parameter Object Properties and CollectionsADO Parameter Object Properties and Collections

    to enable you to reuse a query while changing a small piece of tto enable you to reuse a query while changing a small piece of the query. Forhe query. Forexample, execute that query multiple times, changing only the vaexample, execute that query multiple times, changing only the value of thelue of the

    CustomerIDCustomerID each time the query is executed:each time the query is executed:

    SELECTSELECT ** FROMFROM CustomersCustomers WHEREWHERE CustomerIDCustomerID == ??

    Prop.or Coll. NameProp.or Coll. Name Data TypeData Type DescriptionDescription

    DirectionDirection ParameterDirectionEnumParameterDirectionEnum Indicates which type of parameterIndicates which type of parameter

    you're usingyou're usinginput, output,input, output,

    input/output, or returninput/output, or return

    NameName StringString Contains the name of the ParameterContains the name of the Parameterobjectobject

    SizeSize LongLong Returns the defined size for a fieldReturns the defined size for a field

    TypeType DataTypeEnumDataTypeEnum Returns the data type for a fieldReturns the data type for a field

    ValueValue VariantVariant the current value for a fieldthe current value for a field

    ADO Parameter Object MethodADO Parameter Object Method

    Method NameMethod Name DescriptionDescription

    AppendChunkAppendChunk Adds chunks of string or binary data to the Parameter objectAdds chunks of string or binary data to the Parameter object

    Th ADO R d d S ObjTh ADO R d d St Obj t

  • 8/2/2019 ADO Lecture

    36/57

    The ADO Record and Stream ObjectsThe ADO Record and Stream Objects

    Which 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 standardamong web servers called Web Distributed Authoring and Versioning(WebDAV), which defines a method of interaction with the filesmaintained by the web server. This standard set of interfaces allowsweb 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). Youcould use such a provider to communicate with your mail server byusing ADO to build e-mail applications like Microsoft Outlook.

    ADO Record ObjectADO Record Object

  • 8/2/2019 ADO Lecture

    37/57

    jj

    OLE DB providers for traditional relational databases don't suppOLE DB providers for traditional relational databases don't supportort

    Record objectRecord object

    Hierarchical DataHierarchical Data

    File 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 reWhile a file might resemble a row in a table in a traditional re lational database, a directorylational 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'sCall a Record object's GetChildrenGetChildrenmethod, and you'll receive amethod, and you'll receive a RecordsetRecordset object thatobject that

    contains the child data (the records) associated with that Recorcontains the child data (the records) associated with that Record object.d 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 datecreated, but they also expose unique attributes. For example, filesgenerally have an application associated with them, and directoriesgenerally contain information about whether they're visible as anetwork share. Because this structure of files and subdirectories

    within a directory exposes different attributes, the attribute data isconsidered nonrectangular. With Recordset object, you'd see only the common attributes

    (columns of data) that are exposed by both the files andsubdirectories. Examining a file and a subdirectory as individualRecord objects will expose all the attributes of both structures

  • 8/2/2019 ADO Lecture

    38/57

  • 8/2/2019 ADO Lecture

    39/57

    ADO Record Object Functions and MethodsADO Record Object Functions and Methods

    FuncFuncor Method Nameor Method Name DescriptionDescription

    CancelCancel Cancels an asynchronous action on the Record objectCancels an asynchronous action on the Record object

    CloseClose Closes an open Record objectCloses an open Record object

    CopyRecordCopyRecord Copies the Record object to another locationCopies the Record object to another location

    DeleteRecordDeleteRecord Deletes the Record objectDeletes the Record object

    GetChildrenGetChildren 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 location

    OpenOpen Opens an existing Record object or creates a new RecordOpens an existing Record object or creates a new Record

    objectobject

  • 8/2/2019 ADO Lecture

    40/57

    ADOADO RecorsetRecorset object Properties & collectionsobject Properties & collections

    ActiveConnectionActiveConnection

    FieldsFields

    ModeMode specify permissions for modificationspecify 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

  • 8/2/2019 ADO Lecture

    41/57

    ADO Stream ObjectADO Stream Object

    Use Stream object in conjunction with the Record object to accesUse Stream object in conjunction with the Record object to access documents document--

    based data.based data.

    Working with Document DataWorking with Document Data

    While the Record object allows you to interact with the structurWhile the Record object allows you to interact with the structure of documents,e of documents,

    the Stream object lets you access the contents of those documentthe Stream object lets you access the contents of those documents.s.

    Stream.Open Record,Stream.Open Record, adModeReadWriteadModeReadWrite,, adOpenStreamFromRecordadOpenStreamFromRecordStream.Position = 0Stream.Position = 0

    Stream.Stream.LoadFromFileLoadFromFile strPathToFilestrPathToFile

    Stream.FlushStream.Flush

    AADO Stream Object Functions and MethodsDO Stream Object Functions and Methods

    FuncFuncor Method Nameor Method Name DescriptionDescriptionCancelCancel Cancels a pending asynchronous call to a Stream objectCancels a pending asynchronous call to a Stream object

    CloseClose Closes an open Stream objectCloses an open Stream object

    FlushFlush Flushes the contents stored in the Stream object's bufferFlushes the contents stored in the Stream object's buffer

    LoadFromFileLoadFromFile Loads the contents of a file into the streamLoads the contents of a file into the stream

    OpenOpen Opens the Stream objectOpens the Stream objectReadRead Reads binary data from the streamReads binary data from the stream

    SaveToFileSaveToFile Persist dataPersist data

    WriteWrite Append data to the streamAppend data to the stream

    Open MethodOpen Method

    The Open method opens a Stream Object from a Record object or URThe Open method opens a Stream Object from a Record object or URLL

    CursorsCursors

  • 8/2/2019 ADO Lecture

    42/57

    CursorsCursors

    ForwardForward--Only CursorsOnly Cursors

    TheThe adOpenForwardOnlyadOpenForwardOnly constant, aconstant, a CursorTypeEnumCursorTypeEnum type, correspondstype, correspondsto this type of cursor. It is the default value for ato this type of cursor. It is the default value for a RecordsetRecordset object'sobject's

    CursorTypeCursorType property when you use the default value (property when you use the default value (adUseServeradUseServer) for the) for the

    RecordsetRecordset object'sobject's CursorLocationCursorLocation property. ADO retrieves from the cursorproperty. ADO retrieves from the cursor

    up to the number of records specified by theup to the number of records specified by the CacheSizeCacheSize property in aproperty in a

    Variant array, and then when you navigate beyond the data in theVariant array, and then when you navigate beyond the data in the cache,cache,ADO retrieves the next set of recordsADO retrieves the next set of records

  • 8/2/2019 ADO Lecture

    43/57

    FirehoseFirehose CursorsCursors

    forwardforward--only, readonly, read--only, and one record at a time.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. IfSQL Server can support only one active query on a connection. If you openyou open

    aa firehosefirehose cursor and do not fetch all of the data, and then close that cucursor and do not fetch all of the data, and then close that cursor,rsor,you've tied up that connection.you've tied up that connection.

    OLE DBOLE DBthe technology on which ADO is basedthe technology on which ADO is based provider will simplyprovider will simply

    request another connection. See three separate connections to yorequest another connection. See three separate connections to your SQLur SQL

    Server database:Server database:

    SetSet cnNorthwindcnNorthwind == NewNew ADODB.ConnectionADODB.ConnectioncnNorthwindcnNorthwind..CursorLocationCursorLocation == adUseServeradUseServer

    cnNorthwindcnNorthwind.Open.Open strConnstrConn

    SetSet rsCustomersrsCustomers == cnNorthwindcnNorthwind.Execute("SELECT.Execute("SELECT ** FROMFROM Customers")Customers")

    SetSet rsOrdersrsOrders == cnNorthwindcnNorthwind.Execute("SELECT.Execute("SELECT ** FROMFROM Orders")Orders")

    SetSet rsProductsrsProducts == cnNorthwindcnNorthwind.Execute("SELECT.Execute("SELECT ** FROMFROM Products")Products")

    /Adding New ADODB./Adding New ADODB.RecordsetRecordset beforebefore rsrs.Open.Open SQLstringSQLstring for thefor the

    code above, results in constructing 3 separate static cursors /code above, results in constructing 3 separate static cursors /

    St ti CStatic Cursors

  • 8/2/2019 ADO Lecture

    44/57

    Static CursorsStatic Cursors

    supports scrolling forwardsupports scrolling forward andandbackward. 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

    KeysetKeyset CursorsCursors

  • 8/2/2019 ADO Lecture

    45/57

    KeysetKeyset CursorsCursors

    Not only does aNot only does a keysetkeyset cursor allow you to update data, but it alsocursor 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 yourkeyset cursor, you can't see new records . The data in the keyset (rememberthat 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 thenext 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.

  • 8/2/2019 ADO Lecture

    46/57

    Dynamic CursorsDynamic Cursors

    Can contain records that other users have added since initially

    submitted the query

    ClientClient Side CursorsSide Cursors

  • 8/2/2019 ADO Lecture

    47/57

    ClientClient--Side CursorsSide Cursors

    a 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 Updateor UpdateBatch

    method

  • 8/2/2019 ADO Lecture

    48/57

    DatabaseDatabase--Specific Cursor ConsiderationsSpecific Cursor Considerations

    ServerServer--Side Cursors with SQL ServerSide Cursors with SQL Server

    1."cursors are evil,"1."cursors are evil,"

    2. When you use a server2. When you use a server--side cursor with the SQL Server OLE DB provider orside cursor with the SQL Server OLE DB provider or

    ODBC driver, you're using a cursor that's maintained by SQL ServODBC driver, you're using a cursor that's maintained by SQL Server itself.er itself.3. It makes much more sense for your database system to do what3. It makes much more sense for your database system to do what it's designed toit's designed to

    dodostore your data and process queriesstore your data and process queriesrather than expend its resourcesrather than expend its resources

    storing the results of your queriesstoring the results of your queries

    4. if you're using server4. if you're using server--side cursors in your application, you need a liveside 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 datab5. As you add more users, you add more connections to your database, and thease, and the

    same instance of SQL Server needs to maintain the cursors for easame instance of SQL Server needs to maintain the cursors for each user.ch user.

    6. server6. server--side cursors in your ADO and SQL Server application is a bad ideside cursors in your ADO and SQL Server application is a bad idea.a.

  • 8/2/2019 ADO Lecture

    49/57

    ServerServer--Side Cursors with AccessSide Cursors with Access

    1. Both the Access OLE DB provider and the Access ODBC driver su1. Both the Access OLE DB provider and the Access ODBC driver supportpport

    serverserver--side cursors.side cursors.

    2. The term "server" is a little misleading when it comes to ser2. The term "server" is a little misleading when it comes to serverver--sideside

    cursors in Access.cursors in Access.

    3. With SQL Server, the database server maintains the cursor Wit3. With SQL Server, the database server maintains the cursor With Access,h Access,the OLE DB provider and ODBC driver have to do a great deal morethe OLE DB provider and ODBC driver have to do a great deal more workwork

    4. When using a client4. When using a client--side cursor with an Access database, you'reside cursor with an Access database, you're

    essentially moving data from the Access cursor engine to the ADOessentially moving data from the Access cursor engine to the ADO CursorCursor

    Engine. The Jet 4.0 OLE DB Provider or ODBC driver processes thEngine. The Jet 4.0 OLE DB Provider or ODBC driver processes the query,e query,

    generates the results, and then has to pass all of this data togenerates the results, and then has to pass all of this data to the ADO Cursorthe ADO CursorEngine one record at a time.Engine one record at a time.

    5. So should you simply not use client5. So should you simply not use client--side cursors with Access databases?side cursors with Access databases?

    Not so fast. Some ofNot so fast. Some of ADO'sADO's functionality (persistingfunctionality (persisting RecordsetsRecordsets to file, batchto file, batch

    updating, sortingupdating, sorting RecordsetsRecordsets..) is available only with client..) is available only with client--sideside RecordsetsRecordsets..

    Plus, if you're using aPlus, if you're using a keysetkeyset or dynamic cursor to store the results of youror dynamic cursor to store the results of yourAccess queries, the OLE DB provider or ODBC driver still needs tAccess queries, the OLE DB provider or ODBC driver still needs to examineo examine

    the database every timethe database every time

    ServerServer Side Cursors with OracleSide Cursors with Oracle

  • 8/2/2019 ADO Lecture

    50/57

    ServerServer--Side Cursors with OracleSide Cursors with Oracle

    1. there are no OLE DB providers or ODBC drivers for Oracle that1. there are no OLE DB providers or ODBC drivers for Oracle thatsupport cursors outside stored procedures yet.support cursors outside stored procedures yet.

    2. Microsoft ODBC driver for Oracle has always supported cursors2. Microsoft ODBC driver for Oracle has always supported cursors..

    You can get aYou can get a keysetkeyset cursor with the Microsoft ODBC driver forcursor with the Microsoft ODBC driver for

    Oracle. How is this possible?The Microsoft ODBC driver for OraclOracle. How is this possible?The Microsoft ODBC driver for Oracleeactually implements the cursor in a way that is somewhat similaractually implements the cursor in a way that is somewhat similar toto

    how the Access OLE DB provider and ODBC driver implementhow the Access OLE DB provider and ODBC driver implement

    cursors. For acursors. For a keysetkeyset cursor, the Microsoft ODBC driver for Oraclecursor, the Microsoft ODBC driver for Oracle

    requestsrequests keysetkeyset information for the records that satisfy the query'sinformation for the records that satisfy the query's

    criteriacriteria

    3. less stress on the database server. The data in the cursor is3. less stress on the database server. The data in the cursor is

    cached in the Microsoft ODBC driver for Oracle, and the Oraclecached in the Microsoft ODBC driver for Oracle, and the Oracle

    server does what it does bestserver does what it does bestit maintains data and processesit maintains data and processes

    queries.queries.

    Updating Your DatabaseUpdating Your Database

  • 8/2/2019 ADO Lecture

    51/57

    1. Action Queries1. Action Queries

    UPDATEUPDATE CustomersCustomers SETSET BalanceDueBalanceDue == 100100 WHEREWHERE CustomerIDCustomerID == 77

    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):

    DimDimcnDatabasecnDatabaseAsAsADODB.ConnectionADODB.Connection

    strSQLstrSQL =="UPDATE"UPDATECustomersCustomersSETSETBalanceDueBalanceDue=100=100WHEREWHERECustomerIDCustomerID=7=7cnDatabasecnDatabase.Execute.ExecutestrSQLstrSQL,, intRowsAffectedintRowsAffected,, __

    adCmdExecuteNoRecordsadCmdExecuteNoRecords++adCmdTextadCmdText

    MsgBoxMsgBoxintRowsAffectedintRowsAffected&& ""record(s)record(s)affected.affected.

    pro&cons: flexibility, universal support, easy multipro&cons: flexibility, universal support, easy multi--userusersupport, great deal of codesupport, great deal of code

    2. Stored Procedures

    Many database administrators (DBAs) allow users toperform updates only through stored procedures

    because of the level of control they offer.

  • 8/2/2019 ADO Lecture

    52/57

    33. Using Updatable. Using Updatable RecordsetsRecordsets

    Used properly updatableUsed properly updatable RecordsetsRecordsets can save you more time thancan save you more time than

  • 8/2/2019 ADO Lecture

    53/57

    Used properly, updatableUsed properly, updatable RecordsetsRecordsets can save you more time thancan save you more time than

    anything sold in an infomercial.anything sold in an infomercial.

    strSQLstrSQL == "SELECT"SELECT ** FROMFROM CustomersCustomers

    SetSet rsCustomersrsCustomers == NewNew ADODB.ADODB.RecordsetRecordset

    rsCustomersrsCustomers.Open.Open strSQLstrSQL,, cnDatabasecnDatabase,, adOpenKeysetadOpenKeyset,,__

    adLockOptimisticadLockOptimistic,, adCmdTextadCmdText

    rsCustomersrsCustomers("("BalanceDueBalanceDue").Value").Value == rsCustomersrsCustomers("("BalanceDueBalanceDue").Value").Value ++ 5050rsCustomersrsCustomers.Update.Update

    Updatable Server-Side Recordsets

    When you modify the Value property of the various Field objects in your Recordset andthen call the Recordset's Updatemethod, ADO passes that information to the server-sidecursor 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 databaseas you modify the contents of the cursor.

    Access OLE DB provider and ODBC driver manage the cursor & directly communicate withdatabase. 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 makemodifications in the DB.

    di d f d i d b b idi d t f d ti d t b b i idid R dR d t

  • 8/2/2019 ADO Lecture

    54/57

    disadvantages of updating your database by using serverdisadvantages of updating your database by using server--sideside RecordsetsRecordsets::

    1. Server1. Server--sideside RecordsetsRecordsets require a live connection to your database.require a live connection to your database.2. Server2. Server--sideside RecordsetsRecordsets sometimes scale poorly insometimes scale poorly in multiusermultiuser situations.situations.

    3. Because server3. Because server--sideside RecordsetsRecordsets rely on the database system, the OLE DB provider,rely on the database system, the OLE DB provider,

    or the ODBC driver to actually update the database, you might neor the ODBC driver to actually update the database, you might need to develop codeed to develop code

    that is specific to the type of database you're using. For exampthat is specific to the type of database you're using. For example, Microsoft Access andle, Microsoft Access and

    SQL Server do not handle optimistic updates from live cursors thSQL Server do not handle optimistic updates from live cursors the same way.e 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 acursor thats maintained by the database, OLEDB provider or ODBC driver, ADO retrieves theresults 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 successfullyupdated the data in your database.

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

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

  • 8/2/2019 ADO Lecture

    55/57

    In-memory Representations of Data

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

    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, whichassembles the data from the various database tables into a singleresult table.

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

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

  • 8/2/2019 ADO Lecture

    56/57

    Sharing Data Between ApplicationsSharing Data Between Applications

    To transmit an ADO disconnectedTo transmit an ADO disconnected recordsetrecordset from one component to another youfrom one component to another you

  • 8/2/2019 ADO Lecture

    57/57

    To transmit an ADO disconnectedTo transmit an ADO disconnected recordsetrecordset from one component to another, youfrom one component to another, you

    use COM marshalling. To transmit data in ADO.NET, you use a datause COM marshalling. To transmit data in ADO.NET, you use a dataset, which canset, which can

    transmit an XML stream.transmit an XML stream.The transmission of XML files offers the following advantages ovThe transmission of XML files offers the following advantages over COMer COM

    marshalling:marshalling:

    Richer data typesRicher data types

    COM marshalling provides a limited set of data typesCOM marshalling provides a limited set of data types those defined by the COMthose defined by the COM

    standard. Because the transmission of datasets in ADO.NET is basstandard. Because the transmission of datasets in ADO.NET is based on an XMLed on an XML

    format, there is no restriction on data types.format, there is no restriction on data types.

    PerformancePerformance

    Transmitting a large ADOTransmitting a large ADO recordsetrecordset or a large ADO.NET dataset can consumeor a large ADO.NET dataset can consume

    network resources. ADO.NET offers performance advantage, in thanetwork resources. ADO.NET offers performance advantage, in that ADO.NETt ADO.NETdoes not require datadoes not require data--type conversions. ADO, which requires COM marshalling totype conversions. ADO, which requires COM marshalling to

    transmit records sets among components, does require that ADO datransmit records sets among components, does require that ADO data types beta types be

    converted to COM data types.converted to COM data types.

    Penetrating FirewallsPenetrating Firewalls

    A firewall can interfere with two components trying to transmitA firewall can interfere with two components trying to transmit disconnected ADOdisconnected ADOrecordsetsrecordsets. Remember, firewalls are typically configured to allow HTML tex. Remember, firewalls are typically configured to allow HTML text tot to

    pass, but to prevent systempass, but to prevent system--level requests (such as COM marshalling) fromlevel requests (such as COM marshalling) from

    passing.passing.

    Because components exchange ADO.NET datasets using XML, firewallBecause components exchange ADO.NET datasets using XML, firewalls can allows can allow

    datasets to pass.datasets to pass.