active data object

Click here to load reader

Upload: tyrone-bean

Post on 02-Jan-2016

68 views

Category:

Documents


0 download

DESCRIPTION

Active Data Object. Yen-Cheng Chen Department of Information Management Ming Chuan University Dec. 1999. Note: Based on Dr. J.L.Wang’s Presentation. Outlines. ADO Overview ADO Object Model ADO Objects Connection Command & Parameters Recordset & Fields. ADO Overview. - PowerPoint PPT Presentation

TRANSCRIPT

  • Active Data ObjectYen-Cheng ChenDepartment of Information ManagementMing Chuan UniversityDec. 1999Note: Based on Dr. J.L.Wangs Presentation

  • OutlinesADO OverviewADO Object ModelADO Objects Connection Command & Parameters Recordset & Fields

  • ADO OverviewADO is Microsoft's strategic, high-level interface to all kinds of data.ADO provides consistent, high-performance access to data, whether you're creating a front-end database client or middle-tier business object using an application, tool, language, or even an Internet browser.ADO is the single data interface you need to know for 1- to n-tier client/server and Web-based data-driven solution development.

  • ADO Overview (Cont.)ADO is designed as an easy-to-use application level interface to Microsoft's newest and most powerful data access paradigm, OLE DB. OLE DB provides high-performance access to any data source, including relational and non-relational databases, email and file systems, text and graphics, custom business objects, and more.

  • UniversalDataAccess

  • ADO (Objects)Connection Command SQL Parameter SQL Recordset Field Recordset Error Property ADO

  • ADO (Collections)Errors Error Parameters Command Parameter Fields Recordset Field Properties Connection CommandRecordset Field Property

  • ADO Objects

  • ADO Object Model

  • ADO (Connection) SQL (Command) SQL (Parameter) (CommandConnection Recordset) (Recordset)

  • ADO () (Recordset) (Recordset) (Recordset) (Connection)

  • ADO ObjectsConnection Establish an active connection that allows us to gain access to data stored in a databaseCommandObtain records, execute SQL queries, or manipulate the data

  • ADO Objects (Cont.)RecordsetAccess the data that is returned from executing an SQL query

  • Property collectionError collectionConnection ObjectField collectionProperty collectionParameter collectionProperty collectionRecordset ObjectCommand object

  • Connection Object 1/2ConnectionRepresent the physical link between applications and the remote database serverAll communications between Recordset or Commands and the back-end database is negotiated through the connection

  • Connection Object 2/2TransactionMake the interaction with the database bulletproofA series changes can be grouped together to look like a single, all-or-nothing change

  • Connection Object: Basic FlowCreate an instance of the Connection objectOpen a connection: Data Source Name (DSN)Execute commands: SQL CommandClose the connectionRelease the object resource

  • Connection Object: Basic CommandsCreate an Instance of Connection ObjectVB: Dim conn As New ADODB.ConnectionVBScript (ASP): Set conn=Server.CreateObject(ADODB.Conneciton)Open a connection conn.Open DSN, username, passwordExecute an execution, the result, if any, is stored in a recordsetrs = conn.Execute SQL COMMANDClose the connection conn.CloseFree the object resourceSet conn = Nothing

  • Data Source Name (DSN)

  • VB Example: Connection

    Sub main()Dim conn As New ADODB.Connectionconn.Open "dsnNW", "nw", "nw123"Set rs = conn.Execute("select * from ")While Not rs.EOF Debug.Print rs(1) & ":" & rs("") rs.MoveNextWendrs.Closeconn.CloseSet rs = NothingSet conn = NothingEnd Sub

  • Connection.Execute Method row-returning connection.Execute CommandText, RecordsAffected, Options row-returning Set recordset = connection.Execute (CommandText, RecordsAffected, Options)

  • Connection.Execute methodCommandTextSQL commandStored procedureA command or procedure that already exists in the source database systemRecordAffectedADO will set it to the number of affected records

  • Connection Object: Execute methodOptionsAdCmdUnknown0Unknown (default)AdCmdText1A text definition of a command (SQL)adCmdTable2The name of a table (create a recordset)Set rs = conn.Execute(, adCmdTable)adCmdStoreProc3A stored procedure, or query(in the data source )

  • TransactionBegins a new transactionconn.BeginTransSaves any changes and ends the transactionconn.CommitTrans Cancel any changes and ends the transactionconn.RollbackTrans

  • Connection TransactionPerform a series of updates on a data sourceGet the system to store up all the changes, and then commit them in one goBefore actually commit the change, the changes can be rolling back

  • Set ObjCon=Server.CreateObject(ADODB.Conneciton)ObjCon.Open DSNObjCon.BeginTransObjCon.Execute SQL COMMANDIf Conditions Then ObjCon.CommitTrans// Serve any chanegsElse ObjConn.RollbackTrans// Cancel any changesEnd IfObjCon.CloseSet ObjCon = Nothing

  • Command ObjectA Command object is a definition of a specific command that you intend to execute against a data source.Provide methods and properties to manipulate individual commandsCollectionsParameters, PropertiesMethodsCreateParameter, ExecutePropertiesActiveConnection, CommandText, CommandTimeout, CommandType, Name, Prepared, State

  • Command Object

    MethodsCreateParameter: Create a new Parameter object that can be appended to the Parameters collectionsExecute: Execute the SQL statement or stored procedurePropertyActiveConnection: Active one connection to be used by command object (DSN)CommandText: Text of a command to be executeCommandTimeout: No. of second for finishing a commandCommandType: adCmdText(1), adCmdTable(2), adCmdStoreProc(3),adCmdUnknown(4) Prepared: Whether to create a prepared statement before execution (a command could be executed for multiple times)

  • Command: Basic CommandsCreate an instance of the Command objectDim ObjCmd As New ADODB.CommandCreate an active connectionObjCmd.ActiveConnection = DSNExecute a queryObjCmd.CommandText = SQL CommandObjCmd.CommandType = adCmdText SQL queryObjCmd.Prepared = True Compile the statementObjCmd.ExecuteRelease the resource usedObjCmd.ActiveConnection = Nothingset ObjCmd = Nothing

  • Command Object: Execute MethodObjCmd.Execute [RecordAffected,] Parameters, Options

    Execute the query specified by the CommandText propertyRecordAffected and Options (same as Connection )Parameters part specify an array of parameters that are to be used while executing the queryNon-record-producing queries:Update, Insert, DeleteSQL select statement, table name, stroed procedured that returns records: A recordset is returned

  • Parameter ObjectA Parameter object represents a parameter or argument associated with a Command object based on a parameterized query or stored procedure.CollectionsPropertiesMethodsAppendChunkPropertiesAttributes, Direction, Name, NumericScale, Precision, Size, Type, Value

  • Command Object: Execute ExampleDim ObjCmd As New ADODB.CommandObjCmd.ActiveConnection = DSNObjCmd.CommandText = StoredProcObjCmd.CommandType = AdCmdStoredProcObjCmd.Execute Array(tablename, State)ObjCmd.ActiveConnection = Nothing

    Execute the stored procedure, where the table name and the state are specified in the parameter list

  • Command Object:Parameters CollectionThe Command object contains an collection of Parameter objects ( Name: Parameters )Each query can take one or more parametersPropertiesCount: Indicate the total number of parameters in the Parameters collectionMethodsParameters.Append parameterAppend the new created Parameter object to the Parameters collectionParameters.Delete indexRemove a parameter object from the collectionindex: The name or ordinal index of the ParameterSet para = Parameters.Item(index) 'Retrieve a parameterParameters.Refresh Enforce the Parameters collection to read the schema information from the CommandText ( create parameters )

  • Ordered Group of Parameter objectsCommand ObjectParameters Collection Parameter Object Parameter Object Parameter Object

  • Without Parametersln=""fn=""Set cmd = Select * from employee whereSet cmd = cmd & lname= & lnSet cmd = cmd & And fname= & fnSet cm.CommandText = cmdcm.execute

  • With ParametersSet cmd. CommandText = Select * from employee where lname=? And fname=?cm.parameters.refreshcm(0) = ""cm(1) = ""cm.executecm(0) = ""cm.execute

  • With ParametersSet cmd. CommandText = Select * from employee where lname=? And fname=?cm.parameters.refreshcm(0) = lnamecm(1) = fnamecm.executecm(0) = lname2cm.execute

  • Recordset ObjectAssign the query results to a Recordset objectLike a table in memoryCan create recordsets containing the data returned from that queryCan even create a recordset directly, without having to open a connection or execute a command first

  • Recordset FundamentalsOpen the recordsetDim ObjRS As New ADODB.RecordsetObjRS.Open SQL Command, dataSourceNameAccess the data fieldfirstname = ObjRS(fieldName) ' Get the field with field name "fieldName"firstname = ObjRS.Fields(fieldname) ' the same as aboven = ObjRS.Fields.Count get the number of fieldssecondField= ObjRS(2) ' get the 2nd Field of the recordNavigate the recordswhile not ObjRS.EOFdo something with the dataObjRS.MoveNext 'Move the cursor to the next recordWend

  • Recordset: PropertiesAbsolutePage: Page of current positionAbsolutePosition: The original position of the current recordActiveConnection: Active connection objectBOF: Before of first record ( True or False )Bookmark: Return/set a bookmarkCacheSize: Number of records cachedCursorLocation: Server, client, or client batchCursorType: Forwarde, static, dynamic, keysetEditMode: The editing status ( backward compatible with DAO)EOF: End of file ( True or False )Filter: Hide types of recordsLockType: Record locking for edits or updatesMaxRecords: Maximum records retrievedPageSize: Number of pages totalRecordCount: Number of total recordsSource: Source commandStatus: Status of the last action

  • CursorTypeDynamic: adOpenDynamicFully updateable recordset All actions made by other users while the recordset is open are visibleAll types of movement ( up and down )Keyset: adOpenKeysetUpdateable recordsetIt prevents access to records that other users add after it was createdAll types of movementStatic: adOpenStaticStatic non-updateable recordset ( retrieve data )Changes made by other users while the recordset is open arent visibleAll types of movementForward-only: adOpenForwardOnly (default)Static non-updateable recordset Only Scroll forward through the records (MoveNext, GetRows)Actions: Insert, Update & Delete

  • LockTypeadLockReadOnlyCannot alter the data ( no updates, inserts, or deletions )adLockPessimistic ( better at the databases integrity )Record lock during editingLock out everyone else from the record youre editingLock from the time of first change until call the Update methodadLockOptimisticNo lock during editing Lock the record only during the call to UpdateadLockBatchOptimisticNo lock during editing ( modify, insert, delete )Batch update: Lock the records only during the call to UpdateBatch

  • Recordset: MethodAddNew: Create a new record in an updateable recordsetCancelBatch: Cancels a pending batch updateCancelUpdate: Cancel any changes made to the current or a new recordClone: Create identical RecordsetClose: Close an open recordsetDelete: Delete the current recordGetRows: Get multiple recordsMove: Move the position of the current recordMoveFirst, MoveLast, MoveNext, MovePreviousNextRecordset: Move to the next set in multi-set queryOpen: Establish a connection and execute the queryRequery: Refresh the data ( re-execute the original query )Resync: Synchronize data with serverSupports: Determine supported featuresUpdate: Save any changes made to the current recordUpdateBatch: Write all pending batch updates to disk

  • AddNewObjRS.AddNew [ Fields, Values ]Fields: single or array of field namesValues: single or array of valuesWith no parametersAdd a blank recordWith parametersAdd a completely defined new record in one statementUpdate: To truly add the new record to the database

  • ExampleDim fields(2)Dim values(2)fields(0)=Namefields(1)=Agevalues(0)=Wangvalues(1)=1ObjRS.AddNw fields, values

  • DeleteObjRS.Delete affectadAffectCurrent (1)Delete the current record (default )adAffectGroup (2)Delete all records matching the current Filter property

  • Recordset: MovingObjRS.Move n: Moving-n : move backward n recordsn: forward ( integer )ObjRS.AbsolutePosition nn: the current record numberObjRS.MoveFirstObjRS.MoveLastObjRS.MoveNextObjRS.MovePrevious

  • UpdateAlter the field values of the record at the current positionObjRS.Update [fields, values]Update can be omitted for changes made to the current recordMost operations that change current record position cause the equivalent of a call to Update

  • Recordset: Check for EmptyForward-only cursorThe current record position is set to the first recordOther types of recordsetObjRS.MoveFirstCheck the ObjRS.BOF and ObjRS.EOF properties

  • Check the number of recordsFirst move the cursor to the last record to get an accurate valueObjRS.MoveLastCheck the number of recordsObjRS.RecordCount

  • Getting Back a RecordsetCreate a recordset as the result of executing a queryCommand object Connection objectTableEnclose the parameters in bracketsSet ObjRS = connection.Execute ( CommandText, RecordsAffected, Options )Set ObjRS = command.Execute ( RecordsAffected, Parameters, Options )

  • Recordset: Connection

    Dim ObjCon as New ADODB.ConnecitonObjCon.Open DSNSet ObjRS = ObjCon.Execute (SQL COMMAND)'Navigate the records in ObjRSSet ObjRS = NothingSet ObjCon = Nothing

  • Recordset: CommandDim ObjCmd as New ADOBE.CommandObjCmd.ActiveConnection = DSNObjCmd.CommandText = SQL CommandObjCmd.CommandType = adCmdTextSet ObjRS = ObjCmd.Execute' Navigate the records in ObjRSSet ObjRS = NothingSet ObjCmd = Nothing

  • Recordset:Table/ConnectionThis works for either the Connection or the Command objectDim ObjCon as New ADODB.ConnectionObjCon.Open DSNSet ObjRS = ObjCon.Execute(TableName,,adCmdTable)Set ObjRS = NothingSet ObjCon = Nothing

  • Recordset:Table/CommandDim ObjCmd as New ADODB.CommandObjCmd.ActiveConnection = DSNSet ObjRS = ObjCmd.Execute (TableName,,adCmdTable)...

    Dim ObjCmd as New ADODB.CommandObjCmd.ActiveConnection = DSNObjCmd.CommandText = TableNameObjCmd.CommandType = adCmdTableSet ObjRS = ObjCmd.Execute

  • Recordset: Create Recordset DirectlyCreate a recordset Dim ObjRS as New ADODB.RecordsetFill the new recordset with values from the data sourceObjRS.Open Source, ActiveConnection, CursorType, LockType, OptionsSource: A Command object, SQL statement, table name or stored procedureActiveConnection: A Connection object, or a Data Source NameCursorTYpe: adOpenForwardOnly (default)LockType: adLockReadOnly (default)Options: The type of query or table represented by Source

  • Recordset:Simple ExamplesDim ObjRS As New ADODB.RecordsetObjRS.Open TableName, DSN, , , adCmdTable

    Dim ObjRS As New ADODB.RecordsetObjDS.Source = TableNameObjDS.ActiveConnection = DNSObjDS.Option = adCmdTableObjDS.Open

  • Recordset:IterationDim ObjCon As New ADODB.ConnectionObjCon.Open DSNSet ObjRS = ObjCon.Execute(TableName, , adCmdTable)ObjRS.MoveFirstDo While Not ObjRS.EOFObjRS.MoveNextLoop

  • Recordset: Fields CollectionEvery Recordset object has a Field collectionContain the data and other information about each field in the current recordMethodRefresh: Update the collection to reflect changes to the field valuesPropertyCount: Return the number of field in the collectionItem: Retrieve the contents of the fields in the collectionObjRS.Fields.Item(fieldname)ObjRS.Fields.Item(0)the first itemObjRS(fieldname)

  • Recordset: Fields ObjectEach member of the Fields collection is itself a Field objectActualSize: The actual length of the fields current valueAttributes: The kinds of data that the field can holdDefineSize: The size or length of the field as defined in the data sourceName: The name of the fieldNumericScale: The number of decimal places in a numeric fieldOriginalValue: The value of the field before any unsaved changes are made Precision: The number of digits in a numeric fieldType: The data type of the fieldUnderlyingValue: The fields current value within the databaseValue: The value currently assigned to the field, even if unsaved