Download ADO Objects - Yen-Cheng Chen / 陳彥錚

Document related concepts
no text concepts found
Transcript
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
• ADO 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 Webbased 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.
Microsoft
UDA
應用程式, Active Server Page
ADO
Universal
Data
Access
OLE DB
ODBC
Database
Data
Storage
Database
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、 Command、
Recordset 或 Field 的 Property 物件。
ADO Objects
ADO Object Model
ADO 物件程式設計模式
• 連接至資料來源 (Connection)。您可以選擇性
地開始交易。
• 您可以選擇性地建立物件,以代表 SQL 指令
(Command)。
• 您可以選擇性地以 SQL 指令的變數參數指定資
料欄、表格,與數值 (Parameter)。
• 執行指令 (Command、Connection,或
Recordset)。
• 若指令傳回整列資料,將資料列儲存在儲存物
件 (Recordset)。
ADO 物件程式設計模式 (續)
• 您可以選擇性地建立儲存物件的檢視,以便排
序、篩選,與巡覽資料 (Recordset)。
• 新增、刪除,或改變行列的方式來編輯資料
(Recordset)。
• 若合適時,以儲存物件中的變更來更新資料
(Recordset)。
• 若使用交易,則須接受或拒絕交易期間所做的
變更。結束交易 (Connection)。
ADO Objects
• Connection
– Establish an active connection that
allows us to gain access to data
stored in a database
• Command
– Obtain records, execute SQL queries,
or manipulate the data
ADO Objects (Cont.)
• Recordset
–Access the data that is returned
from executing an SQL query
Connection Object
Recordset Object
Field collection
Property collection
Command object
Parameter collection
Property collection
Property collection
Error collection
Connection Object 1/2
• Connection
– Represent the physical link between
applications and the remote database
server
– All communications between Recordset
or Commands and the back-end database
is negotiated through the connection
Connection Object 2/2
• Transaction
– Make the interaction with the
database bulletproof
– A series changes can be grouped
together to look like a single, all-ornothing change
Connection Object: Basic Flow
•
•
•
•
Create an instance of the Connection object
Open a connection: Data Source Name (DSN)
Execute commands: SQL Command
Close the connection
• Release the object resource
Connection Object: Basic Commands
• Create an Instance of Connection Object
– VB: Dim conn As New ADODB.Connection
– VBScript (ASP):
Set conn=Server.CreateObject(“ADODB.Conneciton”)
• Open a connection
– conn.Open “DSN”, “username”, “password”
• Execute an execution, the result, if any, is stored
in a recordset
– rs = conn.Execute “SQL COMMAND”
• Close the connection
– conn.Close
• Free the object resource
– Set conn = Nothing
Data Source Name (DSN)
VB Example: Connection
Sub main()
Dim conn As New ADODB.Connection
conn.Open "dsnNW", "nw", "nw123"
Set rs = conn.Execute("select * from 產品資料")
While Not rs.EOF
Debug.Print rs(1) & ":" & rs("單價")
rs.MoveNext
Wend
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
End Sub
Connection.Execute Method
• 對於非 row-returning 指令字串:
– connection.Execute CommandText,
RecordsAffected, Options
• 對於 row-returning 指令字串:
– Set recordset = connection.Execute
(CommandText, RecordsAffected, Options)
Connection.Execute method
• CommandText
– SQL command
– Stored procedure
• A command or procedure that already exists in the
source database system
• RecordAffected
– ADO will set it to the number of affected
records
Connection Object: Execute method
• Options
– AdCmdUnknown0
• Unknown (default)
– AdCmdText
1
• A text definition of a command (SQL)
– adCmdTable
2
• The name of a table (create a recordset)
• Set rs = conn.Execute(“產品資料”, adCmdTable)
– adCmdStoreProc 3
– A stored procedure, or query(in the data source )
Transaction
• Begins a new transaction
– conn.BeginTrans
• Saves any changes and ends the transaction
– conn.CommitTrans
• Cancel any changes and ends the
transaction
– conn.RollbackTrans
Connection Transaction
• Perform a series of updates on a data source
– Get the system to store up all the changes, and
then commit them in one go
• Before actually commit the change, the
changes can be rolling back
Set
ObjCon=Server.CreateObject(“ADODB.Conneciton”)
ObjCon.Open “DSN”
ObjCon.BeginTrans
ObjCon.Execute “SQL COMMAND”
If Conditions Then
ObjCon.CommitTrans
// Serve any chanegs
Else
ObjConn.RollbackTrans // Cancel any changes
End If
ObjCon.Close
Set ObjCon = Nothing
Command Object
• A 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 commands
• Collections
– Parameters, Properties
• Methods
– CreateParameter, Execute
• Properties
– ActiveConnection, CommandText, CommandTimeout,
CommandType, Name, Prepared, State
Command Object
• Methods
– CreateParameter: Create a new Parameter object that can be
appended to the Parameters collections
– Execute: Execute the SQL statement or stored procedure
• Property
– ActiveConnection: Active one connection to be used by command
object (DSN)
– CommandText: Text of a command to be execute
– CommandTimeout: No. of second for finishing a command
– CommandType:
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 Commands
• Create an instance of the Command object
– Dim ObjCmd As New ADODB.Command
• Create an active connection
– ObjCmd.ActiveConnection = “DSN”
• Execute a query
–
–
–
–
ObjCmd.CommandText = “SQL Command”
ObjCmd.CommandType = adCmdText ’SQL query
ObjCmd.Prepared = True ‘Compile the statement
ObjCmd.Execute
• Release the resource used
– ObjCmd.ActiveConnection = Nothing
– set ObjCmd = Nothing
Command Object: Execute Method
ObjCmd.Execute [RecordAffected,] Parameters, Options
• Execute the query specified by the CommandText
property
• RecordAffected and Options (same as Connection )
• Parameters part specify an array of parameters that are to
be used while executing the query
• Non-record-producing queries:Update, Insert, Delete
• SQL select statement, table name, stroed procedured that
returns records: A recordset is returned
Parameter Object
• A Parameter object represents a parameter or
argument associated with a Command object
based on a parameterized query or stored
procedure.
• Collections
– Properties
• Methods
– AppendChunk
• Properties
– Attributes, Direction, Name, NumericScale, Precision,
Size, Type, Value
Command Object: Execute Example
Dim ObjCmd As New ADODB.Command
ObjCmd.ActiveConnection = “DSN”
ObjCmd.CommandText = “StoredProc”
ObjCmd.CommandType = AdCmdStoredProc
ObjCmd.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 Collection
• The Command object contains an collection of Parameter objects
( Name: Parameters )
– Each query can take one or more parameters
• Properties
– Count: Indicate the total number of parameters in the Parameters collection
• Methods
– Parameters.Append parameter
• Append the new created Parameter object to the Parameters collection
– Parameters.Delete index
‘Remove a parameter object from the collection
• index: The name or ordinal index of the Parameter
– Set para = Parameters.Item(index) 'Retrieve a parameter
– Parameters.Refresh
• Enforce the Parameters collection to read the schema information from the
CommandText ( create parameters )
Ordered Group of Parameter objects
Command Object
Parameters Collection
Parameter Object
Parameter Object
Parameter Object
Without Parameters
ln="李"
fn="大同"
Set cmd = “Select * from employee where”
Set cmd = cmd & “lname=“ & ln
Set cmd = cmd & “And fname=“ & fn
Set cm.CommandText = cmd
cm.execute
With Parameters
Set cmd. CommandText = “Select * from
employee where lname=? And fname=?”
cm.parameters.refresh
cm(0) = "李"
cm(1) = "大同"
cm.execute
cm(0) = "王"
cm.execute
With Parameters
Set cmd. CommandText = “Select * from
employee where lname=? And fname=?”
cm.parameters.refresh
cm(0) = lname
cm(1) = fname
cm.execute
cm(0) = lname2
cm.execute
Recordset Object
• Assign the query results to a Recordset object
• Like a table in memory
• Can create recordsets containing the data returned from
that query
• Can even create a recordset directly, without having to
open a connection or execute a command first
Recordset Fundamentals
• Open the recordset
Dim ObjRS As New ADODB.Recordset
ObjRS.Open “SQL Command”, “dataSourceName”
• Access the data field
firstname = ObjRS(“fieldName”)
' Get the field with field name "fieldName"
firstname = ObjRS.Fields(“fieldname”) ' the same as above
n = ObjRS.Fields.Count
‘ get the number of fields
secondField= ObjRS(2) ' get the 2nd Field of the record
• Navigate the records
while not ObjRS.EOF
‘do something with the data
ObjRS.MoveNext 'Move the cursor to the next record
Wend
Recordset: Properties
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AbsolutePage: Page of current position
AbsolutePosition: The original position of the current record
ActiveConnection: Active connection object
BOF: Before of first record ( True or False )
Bookmark: Return/set a bookmark
CacheSize: Number of records cached
CursorLocation: Server, client, or client batch
CursorType: Forwarde, static, dynamic, keyset
EditMode: The editing status ( backward compatible with DAO)
EOF: End of file ( True or False )
Filter: Hide types of records
LockType: Record locking for edits or updates
MaxRecords: Maximum records retrieved
PageSize: Number of pages total
RecordCount: Number of total records
Source: Source command
Status: Status of the last action
CursorType
• Dynamic: adOpenDynamic
–
–
–
Fully updateable recordset
All actions made by other users while the recordset is open are visible
All types of movement ( up and down )
• Keyset: adOpenKeyset
–
–
–
Updateable recordset
It prevents access to records that other users add after it was created
All types of movement
• Static: adOpenStatic
–
–
–
Static non-updateable recordset ( retrieve data )
Changes made by other users while the recordset is open aren’t visible
All types of movement
• Forward-only: adOpenForwardOnly (default)
–
–
Static non-updateable recordset
Only Scroll forward through the records (MoveNext, GetRows)
Actions: Insert, Update & Delete
LockType
• adLockReadOnly
– Cannot alter the data ( no updates, inserts, or deletions )
• adLockPessimistic ( better at the database’s integrity )
– Record lock during editing
–
–
Lock out everyone else from the record you’re editing
Lock from the time of first change until call the Update method
• adLockOptimistic
– No lock during editing
–
Lock the record only during the call to Update
• adLockBatchOptimistic
–
–
No lock during editing ( modify, insert, delete )
Batch update: Lock the records only during the call to UpdateBatch
Recordset: Method
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
AddNew: Create a new record in an updateable recordset
CancelBatch: Cancels a pending batch update
CancelUpdate: Cancel any changes made to the current or a new record
Clone: Create identical Recordset
Close: Close an open recordset
Delete: Delete the current record
GetRows: Get multiple records
Move: Move the position of the current record
MoveFirst, MoveLast, MoveNext, MovePrevious
NextRecordset: Move to the next set in multi-set query
Open: Establish a connection and execute the query
Requery: Refresh the data ( re-execute the original query )
Resync: Synchronize data with server
Supports: Determine supported features
Update: Save any changes made to the current record
UpdateBatch: Write all pending batch updates to disk
AddNew
• ObjRS.AddNew [ Fields, Values ]
– Fields: single or array of field names
– Values: single or array of values
• With no parameters
– Add a blank record
• With parameters
– Add a completely defined new record in one
statement
• Update: To truly add the new record to the database
Example
Dim fields(2)
Dim values(2)
fields(0)=“Name”
fields(1)=“Age”
values(0)=“Wang”
values(1)=1
ObjRS.AddNw fields, values
Delete
• ObjRS.Delete affect
– adAffectCurrent (1)
• Delete the current record (default )
– adAffectGroup (2)
• Delete all records matching the current Filter
property
Recordset: Moving
• ObjRS.Move n: Moving
-n : move backward n records
n: forward ( integer )
• ObjRS.AbsolutePosition n
n: the current record number
• ObjRS.MoveFirst
• ObjRS.MoveLast
• ObjRS.MoveNext
• ObjRS.MovePrevious
Update
• Alter the field values of the record at the current
position
• ObjRS.Update [fields, values]
• Update can be omitted for changes made to
the current record
– Most operations that change current record
position cause the equivalent of a call to Update
Recordset: Check for Empty
• Forward-only cursor
The current record position is set to the first record
• Other types of recordset
ObjRS.MoveFirst
• Check the ObjRS.BOF and ObjRS.EOF properties
Check the number of records
• First move the cursor to the last record to
get an accurate value
ObjRS.MoveLast
• Check the number of records
ObjRS.RecordCount
Getting Back a Recordset
• Create a recordset as the result of executing a
query
– Command object
– Connection object
– Table
• Enclose the parameters in brackets
• Set ObjRS = connection.Execute
( CommandText, RecordsAffected, Options )
• Set ObjRS = command.Execute
( RecordsAffected, Parameters, Options )
Recordset: Connection
Dim ObjCon as New ADODB.Conneciton
ObjCon.Open “DSN”
Set ObjRS = ObjCon.Execute (“SQL COMMAND”)
'Navigate the records in ObjRS
…
Set ObjRS = Nothing
Set ObjCon = Nothing
Recordset: Command
Dim ObjCmd as New ADOBE.Command
ObjCmd.ActiveConnection = “DSN”
ObjCmd.CommandText = “SQL Command”
ObjCmd.CommandType = adCmdText
Set ObjRS = ObjCmd.Execute
' Navigate the records in ObjRS
…
Set ObjRS = Nothing
Set ObjCmd = Nothing
Recordset:Table/Connection
• This works for either the Connection or the Command object
• Dim ObjCon as New ADODB.Connection
ObjCon.Open “DSN”
Set ObjRS = ObjCon.Execute(“TableName”,,adCmdTable)
…
Set ObjRS = Nothing
Set ObjCon = Nothing
Recordset:Table/Command
• Dim ObjCmd as New ADODB.Command”
ObjCmd.ActiveConnection = “DSN”
Set ObjRS = ObjCmd.Execute (“TableName”,,adCmdTable)
...
• Dim ObjCmd as New ADODB.Command
ObjCmd.ActiveConnection = “DSN”
ObjCmd.CommandText = “TableName”
ObjCmd.CommandType = adCmdTable
Set ObjRS = ObjCmd.Execute
…
Recordset: Create Recordset Directly
• Create a recordset
Dim ObjRS as New ADODB.Recordset
• Fill the new recordset with values from the data source
ObjRS.Open Source, ActiveConnection, CursorType, LockType, Options
– Source: A Command object, SQL statement, table name or stored procedure
– ActiveConnection: A Connection object, or a Data Source Name
– CursorTYpe: adOpenForwardOnly (default)
– LockType: adLockReadOnly (default)
– Options: The type of query or table represented by Source
Recordset:Simple Examples
• Dim ObjRS As New ADODB.Recordset
ObjRS.Open “TableName”, “DSN”, , , adCmdTable
• Dim ObjRS As New ADODB.Recordset
ObjDS.Source = “TableName”
ObjDS.ActiveConnection = “DNS”
ObjDS.Option = adCmdTable
ObjDS.Open
Recordset:Iteration
Dim ObjCon As New ADODB.Connection
ObjCon.Open “DSN”
Set ObjRS = ObjCon.Execute(“TableName”, , adCmdTable)
ObjRS.MoveFirst
Do While Not ObjRS.EOF
…
ObjRS.MoveNext
Loop
Recordset: Fields Collection
• Every Recordset object has a Field collection
Contain the data and other information about each field in the
current record
• Method
Refresh: Update the collection to reflect changes to the field values
• Property
Count: Return the number of field in the collection
Item: Retrieve the contents of the fields in the collection
ObjRS.Fields.Item(“fieldname”)
ObjRS.Fields.Item(0)
‘the first item
ObjRS(“fieldname”)
Recordset: Fields Object
• Each member of the Fields collection is itself a Field object
ActualSize: The actual length of the field’s current value
Attributes: The kinds of data that the field can hold
DefineSize: The size or length of the field as defined in the data source
Name: The name of the field
NumericScale: The number of decimal places in a numeric field
OriginalValue: The value of the field before any unsaved changes are made
Precision: The number of digits in a numeric field
Type: The data type of the field
UnderlyingValue: The field’s current value within the database
Value: The value currently assigned to the field, even if unsaved