Adocode
Adocode
Use the following code examples to learn how to use the ADO objects, methods, properties, and events.
NOTE
Paste the entire code example into your code editor. The example may not run correctly if partial examples are used or if
paragraph formatting is lost.
Remarks
The Type property is read/write only when the current position is at the beginning of the Stream (Position is 0),
and read-only at any other position.
TheType property determines which methods should be used for reading and writing the Stream. For text
Streams, use ReadText and WriteText. For binary Streams, use Read and Write.
Applies To
Stream Object (ADO )
See Also
RecordType Property (ADO )
Type Property (ADO )
Prepared Property Example (VC++)
11/28/2018 • 2 minutes to read • Edit Online
This example demonstrates the Prepared property by opening two Command objects - one prepared and one not
prepared.
Example
// Prepared_Property_Sample.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
#include <winbase.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void PreparedX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
PreparedX();
::CoUninitialize();
}
void PreparedX() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
_CommandPtr pCmd1 = NULL;
_CommandPtr pCmd2 = NULL;
try {
// Open a connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open (strCnn, "", "", adConnectUnspecified);
// Create two command objects for the same command; one prepared and one not.
TESTHR(pCmd1.CreateInstance(__uuidof(Command)));
pCmd1->ActiveConnection = pConnection;
pCmd1->CommandText = strCmd;
TESTHR(pCmd2.CreateInstance(__uuidof(Command)));
pCmd2->ActiveConnection = pConnection;
pCmd2->CommandText = strCmd;
pCmd2->PutPrepared(true);
DWORD sngEnd=GetTickCount();
float sngNotPrepared = (float)(sngEnd - sngStart) / (float)1000;
sngEnd=GetTickCount();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}
if ( (pConnection->Errors->Count) > 0 ) {
long nCount = pConnection->Errors->Count;
Performance Results:
Not Prepared: 0.016 seconds
Prepared: 0.016 seconds
See Also
Command Object (ADO )
Prepared Property (ADO )
ObjectProxy (ADO - WFC Syntax)
10/1/2018 • 2 minutes to read • Edit Online
An ObjectProxy object represents a server, and is returned by the createObject method of the DataSpace object.
The ObjectProxy class has one method, call, which can invoke a method on the server and return an object
resulting from that invocation.
package com.ms.wfc.data
Methods
Call Method (ADO/WFC Syntax)
Invokes a method on the server represented by the ObjectProxy. Optionally, method arguments may be passed as
an array of objects.
Syntax
Returns
Object
An object resulting from invoking the method.
Parameters
ObjectProxy
An ObjectProxy object that represents the server.
method
A String, containing the name of the method to invoke on the server.
args
Optional. An array of objects that are arguments to the method on the server. Java data types are automatically
converted to data types suitable for use on the server.
Connection Object Properties, Methods, and Events
10/1/2018 • 2 minutes to read • Edit Online
Properties/Collections
Attributes Property
CommandTimeout Property
ConnectionString Property
ConnectionTimeout Property
CursorLocation Property
DefaultDatabase Property
Errors Collection
IsolationLevel Property
Mode Property
Properties Collection
Provider Property
State Property
Version Property
Methods
BeginTrans, CommitTrans, and RollbackTrans Methods
Cancel Method
Close Method
Execute Method (ADO Connection)
Open Method (ADO Connection)
OpenSchema Method
Events
BeginTransComplete, CommitTransComplete, and RollbackTransComplete Events
ConnectComplete and Disconnect Events
ExecuteComplete Event
InfoMessage Event
WillConnect Event
WillExecute Event
See Also
Connection Object (ADO )
RecordTypeEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
These constants do not have ADO/WFC equivalents.
Applies To
RecordType Property (ADO )
MoveRecordOptionsEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
These constants do not have ADO/WFC equivalents.
Applies To
MoveRecord Method (ADO )
Refresh Method Example (VB)
11/19/2018 • 2 minutes to read • Edit Online
This example demonstrates using the Refresh method to refresh the Parameters collection for a stored procedure
Command object.
'BeginRefreshVB
Public Sub Main()
On Error GoTo ErrorHandler
intRoyalty = Trim(strRoyalty)
cmdByRoyalty.Parameters(1) = intRoyalty
Set rstByRoyalty = cmdByRoyalty.Execute()
' Open the Authors table to get author names for display
Set rstAuthors = New ADODB.Recordset
strSQLAuthors = "Authors"
rstAuthors.Open strSQLAuthors, Cnxn, adOpenForwardOnly, adLockPessimistic, adCmdTable
Do Until rstByRoyalty.EOF
strAuthorID = rstByRoyalty!au_id
strAuthorID = rstByRoyalty!au_id
Debug.Print " " & rstByRoyalty!au_id & ", ";
rstAuthors.Filter = "au_id = '" & strAuthorID & "'"
Debug.Print rstAuthors!au_fname & " "; rstAuthors!au_lname
rstByRoyalty.MoveNext
Loop
' clean up
rstByRoyalty.Close
rstAuthors.Close
Cnxn.Close
Set rstByRoyalty = Nothing
Set rstAuthors = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstByRoyalty Is Nothing Then
If rstByRoyalty.State = adStateOpen Then rstByRoyalty.Close
End If
Set rstByRoyalty = Nothing
See Also
Command Object (ADO )
Parameters Collection (ADO )
Refresh Method (ADO )
CompareBookmarks Method Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the CompareBookmarks method. The relative value of bookmarks is seldom needed
unless a particular bookmark is somehow special.
Designate a random row of a Recordset derived from the Authors table as the target of a search. Then display the
position of each row relative to that target.
'BeginCompareBookmarksVB
count = rstAuthors.RecordCount
Debug.Print "Rows in the Recordset = "; count
count = 0
rstAuthors.MoveFirst
' Loop through recordset
Do Until rstAuthors.EOF
Do Until rstAuthors.EOF
result = rstAuthors.CompareBookmarks(rstAuthors.Bookmark, target)
count = count + 1
rstAuthors.MoveNext
Loop
' clean up
rstAuthors.Close
Cnxn.Close
Set rstAuthors = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstAuthors Is Nothing Then
If rstAuthors.State = adStateOpen Then rstAuthors.Close
End If
Set rstAuthors = Nothing
End Sub
'EndCompareBookmarksVB
See Also
CompareBookmarks Method (ADO )
CompareEnum
Recordset Object (ADO )
SeekEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.Seek.FIRSTEQ
AdoEnums.Seek.LASTEQ
AdoEnums.Seek.AFTEREQ
AdoEnums.Seek.AFTER
AdoEnums.Seek.BEFOREEQ
AdoEnums.Seek.BEFORE
Applies To
Seek Method
ADCPROP_ASYNCTHREADPRIORITY_ENUM
10/1/2018 • 2 minutes to read • Edit Online
For an RDS Recordset object, specifies the execution priority of the asynchronous thread that retrieves data.
Use these constants with the Recordset "Background Thread Priority" dynamic property, which is referenced in
the ADO -to-OLE DB Dynamic Property index and documented in the Microsoft Cursor Service for OLE DB
documentation.
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.AdcPropAsyncThreadPriority.ABOVENORMAL
AdoEnums.AdcPropAsyncThreadPriority.BELOWNORMAL
AdoEnums.AdcPropAsyncThreadPriority.HIGHEST
AdoEnums.AdcPropAsyncThreadPriority.LOWEST
AdoEnums.AdcPropAsyncThreadPriority.NORMAL
Connection Object (ADO)
10/1/2018 • 3 minutes to read • Edit Online
Remarks
A Connection object represents a unique session with a data source. In a client/server database
system, it may be equivalent to an actual network connection to the server. Depending on the
functionality supported by the provider, some collections, methods, or properties of a Connection
object may not be available.
With the collections, methods, and properties of a Connection object, you can do the following:
Configure the connection before opening it with the ConnectionString, ConnectionTimeout,
and Mode properties. ConnectionString is the default property of the Connection object.
Set the CursorLocation property to client to invoke the Microsoft Cursor Service for OLE DB,
which supports batch updates.
Set the default database for the connection with the DefaultDatabase property.
Set the level of isolation for the transactions opened on the connection with the
IsolationLevel property.
Specify an OLE DB provider with the Provider property.
Establish, and later break, the physical connection to the data source with the Open and Close
methods.
Execute a command on the connection with the Execute method and configure the execution
with the CommandTimeout property.
NOTE
To execute a query without using a Command object, pass a query string to the Execute method of
a Connection object. However, a Command object is required when you want to persist the
command text and re-execute it, or use query parameters.
Manage transactions on the open connection, including nested transactions if the provider
supports them, with the BeginTrans, CommitTrans, and RollbackTrans methods and the
Attributes property.
Examine errors returned from the data source with the Errors collection.
Read the version from the ADO implementation used with the Version property.
Obtain schema information about your database with the OpenSchema method.
You can create Connection objects independently of any other previously defined object.
You can execute named commands or stored procedures as if they were native methods on a
Connection object, as shown in the next section. When a named command has the same name as
that of a stored procedure, invoke the "native method call" on a Connection object always execute
the named command instead of the store procedure.
NOTE
Do not use this feature (calling a named command or stored procedure as if it were a native method on the
Connection object) in a Microsoft® .NET Framework application, because the underlying implementation of
the feature conflicts with the way the .NET Framework interoperates with COM.
See Also
Command Object (ADO )
Errors Collection (ADO )
Properties Collection (ADO )
Recordset Object (ADO )
Appendix A: Providers
Recordset Object (ADO)
10/1/2018 • 5 minutes to read • Edit Online
Represents the entire set of records from a base table or the results of an
executed command. At any time, the Recordset object refers to only a
single record within the set as the current record.
Remarks
You use Recordset objects to manipulate data from a provider. When you
use ADO, you manipulate data almost entirely using Recordset objects.
All Recordset objects consist of records (rows) and fields (columns).
Depending on the functionality supported by the provider, some
Recordset methods or properties may not be available.
ADODB.Recordset is the ProgID that should be used to create a
Recordset object. Existing applications that reference the outdated
ADOR.Recordset ProgID will continue to work without recompiling, but
new development should reference ADODB.Recordset.
There are four different cursor types defined in ADO:
Dynamic cursor Allows you to view additions, changes, and
deletions by other users; allows all types of movement through the
Recordset that doesn't rely on bookmarks; and allows bookmarks
if the provider supports them.
Keyset cursor Behaves like a dynamic cursor, except that it
prevents you from seeing records that other users add, and
prevents access to records that other users delete. Data changes by
other users will still be visible. It always supports bookmarks and
therefore allows all types of movement through the Recordset.
Static cursor Provides a static copy of a set of records for you to
use to find data or generate reports; always allows bookmarks and
therefore allows all types of movement through the Recordset.
Additions, changes, or deletions by other users will not be visible.
This is the only type of cursor allowed when you open a client-side
Recordset object.
Forward-only cursor Allows you to only scroll forward through
the Recordset. Additions, changes, or deletions by other users will
not be visible. This improves performance in situations where you
need to make only a single pass through a Recordset.
Set the CursorType property prior to opening the Recordset to choose
the cursor type, or pass a CursorType argument with the Open method.
Some providers don't support all cursor types. Check the documentation
for the provider. If you don't specify a cursor type, ADO opens a forward-
only cursor by default.
If the CursorLocation property is set to adUseClient to open a
Recordset, the UnderlyingValue property on Field objects is not
available in the returned Recordset object. When used with some
providers (such as the Microsoft ODBC Provider for OLE DB in
conjunction with Microsoft SQL Server), you can create Recordset
objects independently of a previously defined Connection object by
passing a connection string with the Open method. ADO still creates a
Connection object, but it doesn't assign that object to an object variable.
However, if you are opening multiple Recordset objects over the same
connection, you should explicitly create and open a Connection object;
this assigns the Connection object to an object variable. If you do not
use this object variable when opening your Recordset objects, ADO
creates a new Connection object for each new Recordset, even if you
pass the same connection string.
You can create as many Recordset objects as needed.
When you open a Recordset, the current record is positioned to the first
record (if any) and the BOF and EOF properties are set to False. If there
are no records, the BOF and EOF property settings are True.
You can use the MoveFirst, MoveLast, MoveNext, and MovePrevious
methods; the Move method; and the AbsolutePosition, AbsolutePage, and
Filter properties to reposition the current record, assuming the provider
supports the relevant functionality. Forward-only Recordset objects
support only the MoveNext method. When you use the Move methods
to visit each record (or enumerate the Recordset), you can use the BOF
and EOF properties to determine if you've moved beyond the beginning
or end of the Recordset.
Before using any functionality of a Recordset object, you must call the
Supports method on the object to verify that the functionality is
supported or available. You must not use the functionality when the
Supports method returns false. For example, you can use the
MovePrevious method only if Recordset.Supports(adMovePrevious)
returns True. Otherwise, you will get an error, because the Recordset
object might have been closed and the functionality rendered unavailable
on the instance. If a feature you are interested in is not supported,
Supports will return false as well. In this case, you should avoid calling
the corresponding property or method on the Recordset object.
Recordset objects can support two types of updating: immediate and
batched. In immediate updating, all changes to data are written
immediately to the underlying data source once you call the Update
method. You can also pass arrays of values as parameters with the
AddNew and Update methods and simultaneously update several fields
in a record.
If a provider supports batch updating, you can have the provider cache
changes to more than one record and then transmit them in a single call
to the database with the UpdateBatch method. This applies to changes
made with the AddNew, Update, and Delete methods. After you call the
UpdateBatch method, you can use the Status property to check for any
data conflicts in order to resolve them.
NOTE
To execute a query without using a Command object, pass a query string to
the Open method of a Recordset object. However, a Command object is
required when you want to persist the command text and re-execute it, or use
query parameters.
See Also
Connection Object (ADO )
Fields Collection (ADO )
Properties Collection (ADO )
Appendix A: Providers
Execute, Requery, and Clear Methods Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Execute method when run from both a Command object and a Connection
object. It also uses the Requery method to retrieve current data in a Recordset, and the Clear method to clear the
contents of the Errors collection. (The Errors collection is accessed via the Connection object of the
ActiveConnection property of the Recordset.) The ExecuteCommand and PrintOutput procedures are required for
this procedure to run.
'BeginExecuteVB
' clean up
rstTitles.Close
Cnxn.Close
Set rstTitles = Nothing
Set Cnxn = Nothing
Exit Sub
Err_Execute:
' Notify user of any errors that result from
' executing the query
If rstTitles.ActiveConnection.Errors.Count >= 0 Then
For Each Err In rstTitles.ActiveConnection.Errors
MsgBox "Error number: " & Err.Number & vbCr & _
Err.Description
Next Err
End If
' clean up
If Not rstTitles Is Nothing Then
If rstTitles.State = adStateOpen Then rstTitles.Close
End If
Set rstTitles = Nothing
Exit Sub
Err_Execute:
Resume Next
End Sub
End Sub
'EndExecuteVB
See Also
Clear Method (ADO )
Command Object (ADO )
Connection Object (ADO )
Error Object
Execute Method (ADO Command)
Execute Method (ADO Connection)
Recordset Object (ADO )
Requery Method
Save Method
10/1/2018 • 3 minutes to read • Edit Online
Syntax
recordset.Save Destination, PersistFormat
Parameters
Destination
Optional. A Variant that represents the complete path name of the file where the Recordset is to be saved, or a
reference to a Stream object.
PersistFormat
Optional. A PersistFormatEnum value that specifies the format in which the Recordset is to be saved (XML or
ADTG ). The default value is adPersistADTG.
Remarks
The Save Method method can only be invoked on an open Recordset. Use the Open Method (ADO Recordset)
method to later restore the Recordset from Destination.
If the Filter Property property is in effect for the Recordset, then only the rows accessible under the filter are
saved. If the Recordset is hierarchical, then the current child Recordset and its children are saved, including the
parent Recordset. If the Save method of a child Recordset is called, the child and all its children are saved, but
the parent is not.
The first time you save the Recordset, it is optional to specify Destination. If you omit Destination, a new file will
be created with a name set to the value of the Source property of the Recordset.
Omit Destination when you subsequently call Save after the first save, or a run-time error will occur. If you
subsequently call Save with a new Destination, the Recordset is saved to the new destination. However, the new
destination and the original destination will both be open.
Save does not close the Recordset or Destination, so you can continue to work with the Recordset and save
your most recent changes. Destination remains open until the Recordset is closed.
For reasons of security, the Save method permits only the use of low and custom security settings from a script
executed by Microsoft Internet Explorer.
If the Save method is called while an asynchronous Recordset fetch, execute, or update operation is in progress,
then Save waits until the asynchronous operation is complete.
Records are saved beginning with the first row of the Recordset. When the Save method is finished, the current
row position is moved to the first row of the Recordset.
For best results, set the CursorLocation Property (ADO ) property to adUseClient with Save. If your provider
does not support all of the functionality necessary to save Recordset objects, the Cursor Service will provide that
functionality.
When a Recordset is persisted with the CursorLocation property set to adUseServer, the update capability for
the Recordset is limited. Typically, only single-table updates, insertions, and deletions are allowed (dependant
upon provider functionality). The Resync Method method is also unavailable in this configuration.
NOTE
Saving a Recordset with Fields of type adVariant, adIDispatch, or adIUnknown is not supported by ADO and can cause
unpredictable results.
Only Filters in the form of Criteria Strings (e.g. OrderDate > '12/31/1999') affect the contents of a persisted
Recordset. Filters created with an Array of Bookmarks or using a value from the FilterGroupEnum will not affect
the contents of the persisted Recordset. These rules apply to Recordsets created with either client-side or server-
side cursors.
Because the Destination parameter can accept any object that supports the OLE DB IStream interface, you can
save a Recordset directly to the ASP Response object. For more details, please see the XML Recordset
Persistence Scenario.
You can also save a Recordset in XML format to an instance of an MSXML DOM object, as is shown in the
following Visual Basic code:
NOTE
Two limitations apply when saving hierarchical Recordsets (data shapes) in XML format. You cannot save into XML if the
hierarchical Recordset contains pending updates, and you cannot save a parameterized hierarchical Recordset.
A Recordset saved in XML format is saved using UTF -8 format. When such a file is loaded into an ADO Stream,
the Stream object will not attempt to open a Recordset from the stream unless the Charset property of the
stream is set to the appropriate value for UTF -8 format.
Applies To
See Also
Save and Open Methods Example (VB )
Save and Open Methods Example (VC++)
Open Method (ADO Recordset)
Open Method (ADO Stream)
SaveToFile Method
BeginTransComplete, CommitTransComplete, and
RollbackTransComplete Events (ADO)
10/1/2018 • 2 minutes to read • Edit Online
These events will be called after the associated operation on the Connection object finishes executing.
BeginTransComplete is called after the BeginTrans operation.
CommitTransComplete is called after the CommitTrans operation.
RollbackTransComplete is called after the RollbackTrans operation.
Syntax
BeginTransComplete TransactionLevel, pError, adStatus, pConnection
CommitTransComplete pError, adStatus, pConnection
RollbackTransComplete pError, adStatus, pConnection
Parameters
TransactionLevel
A Long value that contains the new transaction level of the BeginTrans that caused this event.
pError
An Error object. It describes the error that occurred if the value of EventStatusEnum is adStatusErrorsOccurred;
otherwise it is not set.
adStatus
An EventStatusEnum status value. When any of these events is called, this parameter is set to adStatusOK if the
operation that caused the event was successful, or to adStatusErrorsOccurred if the operation failed.
These events can prevent subsequent notifications by setting this parameter to adStatusUnwantedEvent before
the event returns.
pConnection
The Connection object for which this event occurred.
Remarks
In Visual C++, multiple Connections can share the same event handling method. The method uses the returned
Connection object to determine which object caused the event.
If the Attributes property is set to adXactCommitRetaining or adXactAbortRetaining, a new transaction starts
after committing or rolling back a transaction. Use the BeginTransComplete event to ignore all but the first
transaction start event.
See Also
ADO Events Model Example (VC++)
BeginTrans, CommitTrans, and RollbackTrans Methods Example (VB )
ADO Event Handler Summary
BeginTrans, CommitTrans, and RollbackTrans Methods (ADO )
EventStatusEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.EventStatus.CANCEL
AdoEnums.EventStatus.CANTDENY
AdoEnums.EventStatus.ERRORSOCCURRED
AdoEnums.EventStatus.OK
AdoEnums.EventStatus.UNWANTEDEVENT
Applies To
WillConnect Event (ADO) WillExecute Event (ADO) WillMove and MoveComplete Events
(ADO)
PersistFormatEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.PersistFormat.ADTG
AdoEnums.PersistFormat.XML
Applies To
Save Method
AddNew Method Example (JScript)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the AddNew method to create a new record with the specified name. Cut and paste the
following code to Notepad or another text editor, and save it as AddNewJS.asp.
<html>
<head>
<title>Add New Method Example (JScript)</title>
<style>
<!--
body {
font-family: 'Verdana','Arial','Helvetica',sans-serif;
BACKGROUND-COLOR:white;
COLOR:black;
}
-->
</style>
</head>
<body>
<h1>AddNew Method Example (JScript)</h1>
<%
if (Request.Form("Addit") == "AddNew")
{
// connection and recordset variables
var Cnxn = Server.CreateObject("ADODB.Connection")
var strCnxn = "Provider='sqloledb';Data Source=" + Request.ServerVariables("SERVER_NAME") + ";" +
"Initial Catalog='Northwind';Integrated Security='SSPI';";
var rsEmployee = Server.CreateObject("ADODB.Recordset");
//record variables
var FName = String(Request.Form("FirstName"));
var LName = String(Request.Form("LastName"));
try
{
// open connection
Cnxn.Open(strCnxn)
rsEmployee.AddNew();
rsEmployee("FirstName") = FName;
rsEmployee("LastName") = LName;
rsEmployee.Update;
See Also
AddNew Method (ADO )
Recordset Object (ADO )
CancelUpdate Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Cancels any changes made to the current or new row of a Recordset object, or the Fields collection of a Record
object, before calling the Update method.
Syntax
recordset.CancelUpdaterecord.Fields.CancelUpdate
Remarks
Recordset
Use the CancelUpdate method to cancel any changes made to the current row or to discard a newly added
row. You cannot cancel changes to the current row or a new row after you call the Update method, unless the
changes are either part of a transaction that you can roll back with the RollbackTrans method, or part of a batch
update. In the case of a batch update, you can cancel the Update with the CancelUpdate or CancelBatch
method.
If you are adding a new row when you call the CancelUpdate method, the current row becomes the row that
was current before the AddNew call.
If you are in edit mode and want to move off the current record (for example, by using the Move, NextRecordset,
or Close methods), you can use CancelUpdate to cancel any pending changes. You may need to do this if the
update cannot successfully be posted to the data source. For example, an attempted delete that fails due to
referential integrity violations will leave the Recordset in edit mode after a call to Delete.
Record
The CancelUpdate method cancels any pending insertions or deletions of Field objects, and cancels pending
updates of existing fields and restores them to their original values. The Status property of all fields in the Fields
collection is set to adFieldOK.
Applies To
See Also
Update and CancelUpdate Methods Example (VB )
Update and CancelUpdate Methods Example (VC++)
AddNew Method (ADO )
Cancel Method (ADO )
Cancel Method (RDS )
CancelBatch Method (ADO )
CancelUpdate Method (RDS )
EditMode Property
Update Method
Number Property (ADO)
11/13/2018 • 2 minutes to read • Edit Online
Return Value
Returns a Long value that may correspond to one of the ErrorValueEnum constants.
Remarks
Use the Number property to determine which error occurred. The value of the property is a unique number that
corresponds to the error condition.
The Errors collection returns an HRESULT in either hexadecimal format (for example, 0x80004005) or long value
(for example, 2147467259). These HRESULTs can be raised by underlying components, such as OLE DB or even
OLE itself. For more information about these numbers, see Errors (OLE DB ) in the OLE DB Programmer's
Reference.
Applies To
Error Object
See Also
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VB )
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VC++)
Description Property
HelpContext, HelpFile Properties
Source Property (ADO Error)
Append Method (ADO)
10/1/2018 • 4 minutes to read • Edit Online
Appends an object to a collection. If the collection is Fields, a new Field object can be created before it is
appended to the collection.
Syntax
collection.Append object
fields.Append Name, Type, DefinedSize, Attrib, FieldValue
Parameters
collection
A collection object.
fields
A Fields collection.
object
An object variable that represents the object to be appended.
Name
A String value that contains the name of the new Field object, and must not be the same name as any other
object in fields.
Type
A DataTypeEnum value, whose default value is adEmpty, that specifies the data type of the new field. The
following data types are not supported by ADO, and should not be used when appending new fields to a
Recordset Object (ADO ): adIDispatch, adIUnknown, adVariant.
DefinedSize
Optional. A Long value that represents the defined size, in characters or bytes, of the new field. The default value
for this parameter is derived from Type. Fields that have a DefinedSize greater than 255 bytes are treated as
variable length columns. The default for DefinedSize is unspecified.
Attrib
Optional. A FieldAttributeEnum value, whose default value is adFldDefault, that specifies attributes for the new
field. If this value is not specified, the field will contain attributes derived from Type.
FieldValue
Optional. A Variant that represents the value for the new field. If not specified, the field is appended with a null
value.
Remarks
Parameters Collection
You must set the Type property of a Parameter object before appending it to the Parameters collection. If you
select a variable-length data type, you must also set the Size property to a value greater than zero.
Describing parameters yourself minimizes calls to the provider and therefore improves performance when you
use stored procedures or parameterized queries. However, you must know the properties of the parameters
associated with the stored procedure or parameterized query that you want to call.
Use the CreateParameter method to create Parameter objects with the appropriate property settings and use
the Append method to add them to the Parameters collection. This lets you set and return parameter values
without having to call the provider for the parameter information. If you are writing to a provider that does not
supply parameter information, you must use this method to manually populate the Parameters collection in
order to use parameters at all.
Fields Collection
The FieldValue parameter is only valid when adding a Field object to a Record object, not to a Recordset object.
With a Record object, you can append fields and provide values at the same time. With a Recordset object, you
must create fields while the Recordset is closed, and then open the Recordset and assign values to the fields.
NOTE
For new Field objects that have been appended to the Fields collection of a Record object, the Value property must be
set before any other Field properties can be specified. First, a specific value for the Value property must have been
assigned and Update on the Fields collection called. Then, other properties such as Type or Attributes can be accessed.
Field objects of the following data types (DataTypeEnum) cannot be appended to the Fields collection and will cause an
error to occur: adArray, adChapter, adEmpty, adPropVariant, and adUserDefined. Also, the following data types are
not supported by ADO: adIDispatch, adIUnknown, and adIVariant. For these types, no error will occur when appended,
but usage can produce unpredictable results including memory leaks.
Recordset
If you do not set the CursorLocation property before calling the Append method, CursorLocation will be set to
adUseClient (a CursorLocationEnum value) automatically when the Open method of the Recordset object is
called.
A run-time error will occur if the Append method is called on the Fields collection of an open Recordset, or on
a Recordset where the ActiveConnection property has been set. You can only append fields to a Recordset that
is not open and has not yet been connected to a data source. This is typically the case when a Recordset object is
fabricated with the CreateRecordset method or assigned to an object variable.
Record
A run-time error will not occur if the Append method is called on the Fields collection of an open Record. The
new field will be added to the Fields collection of the Record object. If the Record was derived from a
Recordset, the new field will not appear in the Fields collection of the Recordset object.
A non-existent field can be created and appended to the Fields collection by assigning a value to the field object
as if it already existed in the collection. The assignment will trigger the automatic creation and appending of the
Field object, and then the assignment will be completed.
After appending a Field to the Fields collection of a Record object, call the Update method of the Fields
collection to save the change.
Applies To
Fields Collection (ADO )
Parameters Collection (ADO )
See Also
Append and CreateParameter Methods Example (VB )
Append and CreateParameter Methods Example (VC++)
CreateParameter Method (ADO )
Delete Method (ADO Fields Collection)
Delete Method (ADO Parameters Collection)
Delete Method (ADO Recordset)
Update Method
Execute Method (ADO Command)
10/1/2018 • 3 minutes to read • Edit Online
Executes the query, SQL statement, or stored procedure specified in the CommandText or CommandStream
property of the Command object.
Syntax
Set recordset = command.Execute( RecordsAffected, Parameters, Options )
Return Value
Returns a Recordset object reference, a stream, or Nothing.
Parameters
RecordsAffected
Optional. A Long variable to which the provider returns the number of records that the operation affected. The
RecordsAffected parameter applies only for action queries or stored procedures. RecordsAffected does not
return the number of records returned by a result-returning query or stored procedure. To obtain this
information, use the RecordCount property. The Execute method will not return the correct information when
used with adAsyncExecute, simply because when a command is executed asynchronously, the number of
records affected may not yet be known at the time the method returns.
Parameters
Optional. A Variant array of parameter values used in conjunction with the input string or stream specified in
CommandText or CommandStream. (Output parameters will not return correct values when passed in this
argument.)
Options
Optional. A Long value that indicates how the provider should evaluate the CommandText or the
CommandStream property of the Command object. Can be a bitmask value made using CommandTypeEnum
and/or ExecuteOptionEnum values. For example, you could use adCmdText and adExecuteNoRecords in
combination if you want to have ADO evaluate the value of the CommandText property as text, and indicate
that the command should discard and not return any records that might be generated when the command text
executes.
NOTE
Use the ExecuteOptionEnum value adExecuteNoRecords to improve performance by minimizing internal processing. If
adExecuteStream was specified, the options adAsyncFetch and adAsynchFetchNonBlocking are ignored. Do not use
the CommandTypeEnum values of adCmdFile or adCmdTableDirect with Execute. These values can only be used as
options with the Open and Requery methods of a Recordset.
Remarks
Using the Execute method on a Command object executes the query specified in the CommandText property
or CommandStream property of the object.
Results are returned in a Recordset (by default) or as a stream of binary information. To obtain a binary stream,
specify adExecuteStream in Options, then supply a stream by setting Command.Properties("Output
Stream"). An ADO Stream object can be specified to receive the results, or another stream object such as the
IIS Response object can be specified. If no stream was specified before calling Execute with adExecuteStream,
an error occurs. The position of the stream on return from Execute is provider specific.
If the command is not intended to return results (for example, an SQL UPDATE query) the provider returns
Nothing as long as the option adExecuteNoRecords is specified; otherwise Execute returns a closed
Recordset. Some application languages allow you to ignore this return value if no Recordset is desired.
Execute raises an error if the user specifies a value for CommandStream when the CommandType is
adCmdStoredProc, adCmdTable, or adCmdTableDirect.
If the query has parameters, the current values for the Command object's parameters are used unless you
override these with parameter values passed with the Execute call. You can override a subset of the parameters
by omitting new values for some of the parameters when calling the Execute method. The order in which you
specify the parameters is the same order in which the method passes them. For example, if there were four (or
more) parameters and you wanted to pass new values for only the first and fourth parameters, you would pass
Array(var1,,,var4) as the Parameters argument.
NOTE
Output parameters will not return correct values when passed in the Parameters argument.
NOTE
When issuing commands containing URLs, those using the http scheme will automatically invoke the Microsoft OLE DB
Provider for Internet Publishing. For more information, see Absolute and Relative URLs.
Applies To
Command Object (ADO )
See Also
Execute, Requery, and Clear Methods Example (VB )
Execute, Requery, and Clear Methods Example (VBScript)
Execute, Requery, and Clear Methods Example (VC++)
CommandStream Property (ADO )
CommandText Property (ADO )
CommandTypeEnum
Execute Method (ADO Connection)
ExecuteComplete Event (ADO )
CommandStream Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
CommandStream and CommandText are mutually exclusive. When the user sets the CommandStream
property, the CommandText property will be set to the empty string (""). If the user sets the CommandText
property, the CommandStream property will be set to Nothing.
The behaviors of the Command.Parameters.Refresh and Command.Prepare methods are defined by the
provider. The values of parameters in a stream can not be refreshed.
The input stream is not available to other ADO objects that return the source of a Command. For example, if the
Source of a Recordset is set to a Command object that has a stream as its input, Recordset.Source continues to
return the CommandText property, which contains an empty string (""), instead of the stream contents of the
CommandStream property.
When using a command stream (as specified by CommandStream ), the only valid CommandTypeEnum values
for the CommandType property are adCmdText and adCmdUnknown. Any other value causes an error.
Applies To
Command Object (ADO )
See Also
CommandText Property (ADO )
Dialect Property
CommandTypeEnum
Open and Close Methods Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Open and Close methods on both Recordset and Connection objects that have been
opened.
// Open_Close_Methods.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <oledb.h>
#include <stdio.h>
#include <conio.h>
#include "icrsint.h"
END_ADO_BINDING()
public:
CHAR m_sze_fname[21];
ULONG le_fnameStatus;
CHAR m_sze_lname[31];
ULONG le_lnameStatus;
DBDATE m_sze_hiredate;
ULONG le_hiredateStatus;
};
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void OpenX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
OpenX();
::CoUninitialize();
}
void OpenX() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace
_RecordsetPtr pRstEmployee = NULL;
_ConnectionPtr pConnection = NULL;
// Define string variables.
_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");
try {
// open connection and record set
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open(strCnn, "", "", adConnectUnspecified);
TESTHR(pRstEmployee.CreateInstance(__uuidof(Recordset)));
pRstEmployee->Open("Employee", _variant_t((IDispatch *)pConnection,true),
adOpenKeyset, adLockOptimistic, adCmdTable);
// Assign first employee record's hire date to variable, then change hire date.
varDate = emprs.m_sze_hiredate;
printf("Original data\n");
printf("\tName - Hire Date\n");
printf(" %s %s - %d/%d/%d\n\n",
emprs.le_fnameStatus == adFldOK ?
emprs.m_sze_fname : "<NULL>",
emprs.le_lnameStatus == adFldOK ?
emprs.m_sze_lname : "<NULL>",
emprs.le_hiredateStatus == adFldOK ?
emprs.m_sze_hiredate.month : 0,
emprs.le_hiredateStatus == adFldOK ?
emprs.m_sze_hiredate.day : 0,
emprs.le_hiredateStatus == adFldOK ?
emprs.m_sze_hiredate.year : 0);
emprs.m_sze_hiredate.year = 1900;
emprs.m_sze_hiredate.month = 1;
emprs.m_sze_hiredate.day = 1;
picRs->Update(&emprs);
printf("\nChanged data\n");
printf("\tName - Hire Date\n");
printf(" %s %s - %d/%d/%d\n\n",
emprs.le_fnameStatus == adFldOK ?
emprs.m_sze_fname : "<NULL>",
emprs.le_lnameStatus == adFldOK ?
emprs.m_sze_lname : "<NULL>",
emprs.le_hiredateStatus == adFldOK ?
emprs.m_sze_hiredate.month : 0,
emprs.le_hiredateStatus == adFldOK ?
emprs.m_sze_hiredate.day : 0,
emprs.le_hiredateStatus == adFldOK ?
emprs.m_sze_hiredate.year : 0);
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number, pErr->Description);
}
}
}
See Also
Close Method (ADO )
Connection Object (ADO )
Open Method (ADO Connection)
Open Method (ADO Recordset)
Recordset Object (ADO )
IsolationLevel Property
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the IsolationLevel property to set the isolation level of a Connection object. The setting does not take
effect until the next time you call the BeginTrans method. If the level of isolation you request is unavailable, the
provider may return the next greater level of isolation without updating the IsolationLevel property.
The IsolationLevel property is read/write.
NOTE
Remote Data Service Usage When used on a client-side Connection object, the IsolationLevel property can be set only
to adXactUnspecified. Because users are working with disconnected Recordset objects on a client-side cache, there may
be multiuser issues. For instance, when two different users try to update the same record, Remote Data Service simply
allows the user who updates the record first to "win." The second user's update request will fail with an error.
Applies To
Connection Object (ADO )
See Also
IsolationLevel and Mode Properties Example (VB )
IsolationLevel and Mode Properties Example (VC++)
ActiveConnection, CommandText,
CommandTimeout, CommandType, Size, and
Direction Properties Example (JScript)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction
properties to execute a stored procedure. Cut and paste the following code to Notepad or another text editor, and
save it as ActiveConnectionJS.asp.
<html>
<head>
<title>ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties</title>
<style>
<!--
BODY {
font-family: 'Verdana','Arial','Helvetica',sans-serif;
BACKGROUND-COLOR:white;
COLOR:black;
}
.thead {
background-color: #008080;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
color: white;
}
.thead2 {
background-color: #800000;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
color: white;
}
.tbody {
text-align: center;
background-color: #f7efde;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
}
-->
</style>
</head>
<body bgcolor="White">
<%
var iRoyalty = parseInt(Request.Form("RoyaltyValue"));
// check user input
try
{
// open connection
Cnxn.Open(strCnxn);
cmdByRoyalty.CommandText = "byroyalty";
cmdByRoyalty.CommandType = adCmdStoredProc;
cmdByRoyalty.CommandTimeOut = 15;
prmByRoyalty = Server.CreateObject("ADODB.Parameter");
prmByRoyalty.Type = adInteger;
prmByRoyalty.Size = 3;
prmByRoyalty.Direction = adParamInput;
prmByRoyalty.Value = iRoyalty;
cmdByRoyalty.Parameters.Append(prmByRoyalty);
cmdByRoyalty.ActiveConnection = Cnxn;
while (!rsByRoyalty.EOF)
{
// set filter
filter = "au_id='" + rsByRoyalty("au_id")
rsAuthor.Filter = filter + "'";
// get data
strMessage += rsAuthor("au_fname") + " ";
strMessage += rsAuthor("au_lname") + " ";
// end line
strMessage += "</P>";
// show data
Response.Write(strMessage);
<hr>
</body>
</html>
<!-- EndActiveConnectionJS -->
See Also
ActiveCommand Property (ADO )
Command Object (ADO )
CommandText Property (ADO )
CommandTimeout Property (ADO )
CommandType Property (ADO )
Connection Object (ADO )
Direction Property
Parameter Object
Record Object (ADO )
Recordset Object (ADO )
Size Property (ADO Parameter)
Filter and RecordCount Properties Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example open a Recordset on the Publishers table in the Pubs database. It then uses the Filter property to
limit the number of visible records to those publishers in a particular country/region. The RecordCount property
is used to show the difference between the filtered and unfiltered recordsets.
'BeginFilterVB
intPublisherCount = rstPublishers.RecordCount
If rstPublishers.RecordCount = 0 Then
MsgBox "No publishers from that country."
Else
' print number of records for the original recordset
' and the filtered recordset
strMessage = "Orders in original recordset: " & _
vbCr & intPublisherCount & vbCr & _
"Orders in filtered recordset (Country = '" & _
strCountry & "'): " & vbCr & _
rstPublishers.RecordCount
MsgBox strMessage
End If
End If
' clean up
' clean up
rstPublishers.Close
Cnxn.Close
Set rstPublishers = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstPublishers Is Nothing Then
If rstPublishers.State = adStateOpen Then rstPublishers.Close
End If
Set rstPublishers = Nothing
End Sub
'EndFilterVB
NOTE
When you know the data you want to select, it's usually more efficient to open a Recordset with an SQL statement. This
example shows how you can create just one Recordset and obtain records from a particular country.
See Also
Filter Property
RecordCount Property (ADO )
Recordset Object (ADO )
XactAttributeEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.XactAttribute.ABORTRETAINING
AdoEnums.XactAttribute.COMMITRETAINING
Applies To
Attributes Property (ADO )
Size Property (ADO Parameter)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the Size property to determine the maximum size for values written to or read from the Value property of a
Parameter object.
If you specify a variable-length data type for a Parameter object (for example, any String type, such as
adVarChar), you must set the object's Size property before appending it to the Parameters collection; otherwise,
an error occurs.
If you have already appended the Parameter object to the Parameters collection of a Command object and you
change its type to a variable-length data type, you must set the Parameter object's Size property before
executing the Command object; otherwise, an error occurs.
If you use the Refresh method to obtain parameter information from the provider and it returns one or more
variable-length data type Parameter objects, ADO may allocate memory for the parameters based on their
maximum potential size, which could cause an error during execution. To prevent an error, you should explicitly
set the Size property for these parameters before executing the command.
The Size property is read/write.
Applies To
Parameter Object
See Also
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(VB )
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(VC++)
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(JScript)
Size Property (ADO Stream)
PositionEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.Position.BOF
AdoEnums.Position.EOF
AdoEnums.Position.UNKNOWN
Applies To
Methods
HRESULT Cancel( );
HRESULT Close( );
HRESULT Flush( );
HRESULT SetEOS( );
HRESULT SkipLine( );
Properties
_bstr_t GetCharset( );
void PutCharset( _bstr_t pbstrCharset );
__declspec(property(get=GetCharset,put=PutCharset)) _bstr_t Charset;
VARIANT_BOOL GetEOS( );
__declspec(property(get=GetEOS)) VARIANT_BOOL EOS;
long GetPosition( );
void PutPosition( long pPos );
__declspec(property(get=GetPosition,put=PutPosition)) long Position;
long GetSize( );
__declspec(property(get=GetSize)) long Size;
See Also
Stream Object (ADO )
PageSize Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the PageSize property to determine how many records make up a logical page of data. Establishing a page
size allows you to use the AbsolutePage property to move to the first record of a particular page. This is useful in
Web-server scenarios when you want to allow the user to page through data, viewing a certain number of
records at a time.
This property can be set at any time, and its value will be used for calculating the location of the first record of a
particular page.
Applies To
Recordset Object (ADO )
See Also
AbsolutePage, PageCount, and PageSize Properties Example (VB )
AbsolutePage, PageCount, and PageSize Properties Example (VC++)
AbsolutePage Property (ADO )
PageCount Property (ADO )
Charset Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Indicates the character set into which the contents of a text Stream should be translated for storage in the internal
buffer of the Stream object.
Remarks
In a text Stream object, text data is stored in the character set specified by the Charset property. The default is
Unicode. The Charset property is used for converting data going into the Stream or coming out of the Stream.
For example, if the Stream contains ISO -8859-1 data and that data is copied to a BSTR, the Stream object will
convert the data to Unicode. The reverse is also true.
For an open Stream, the current Position must be at the beginning of the Stream (0) to be able to set Charset.
Charset is used only with text Stream objects (Type is adTypeText). This property is ignored if Type is
adTypeBinary.
For a code sample, see Step 4: Populate the Details Text Box.
Applies To
Stream Object (ADO )
Prepared Property Example (VB)
11/28/2018 • 2 minutes to read • Edit Online
This example demonstrates the Prepared property by opening two Command objects - one prepared and one not
prepared.
'BeginPreparedVB
' clean up
Cnxn.Close
Set Cnxn = Nothing
Set cmd1 = Nothing
Set cmd2 = Nothing
Exit Sub
ErrorHandler:
' clean up
Set cmd1 = Nothing
Set cmd2 = Nothing
See Also
Command Object (ADO )
Prepared Property (ADO )
Status Property Example (Recordset) (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Status property to display which records have been modified in a batch operation before a
batch update has occurred.
'BeginStatusRecordsetVB
Public Sub Main()
On Error GoTo ErrorHandler
' clean up
rstTitles.Close
Cnxn.Close
Set rstTitles = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstTitles Is Nothing Then
If rstTitles.State = adStateOpen Then
' Cancel the update because this is a demonstration
rstTitles.CancelBatch
rstTitles.Close
rstTitles.Close
End If
End If
Set rstTitles = Nothing
See Also
Status Property (ADO Recordset)
Item Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Set object = collection.Item ( Index )
Return Value
Returns an object reference.
Parameters
Index
A Variant expression that evaluates either to the name or to the ordinal number of an object in a collection.
Remarks
Use the Item property to return a specific object in a collection. If Item cannot find an object in the collection
corresponding to the Index argument, an error occurs. Also, some collections don't support named objects; for
these collections, you must use ordinal number references.
The Item property is the default property for all collections; therefore, the following syntax forms are
interchangeable:
collection.Item (Index)
collection (Index)
Applies To
Axes Collection (ADO MD) Columns Collection (ADOX) CubeDefs Collection (ADO MD)
Dimensions Collection (ADO MD) Errors Collection (ADO) Fields Collection (ADO)
Groups Collection (ADOX) Hierarchies Collection (ADO MD) Indexes Collection (ADOX)
Keys Collection (ADOX) Levels Collection (ADO MD) Members Collection (ADO MD)
Parameters Collection (ADO) Positions Collection (ADO MD) Procedures Collection (ADOX)
This example demonstrates the Source property by opening three Recordset objects based on different data
sources.
// Source_Property_Sample.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void SourceX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
SourceX();
::CoUninitialize();
}
void SourceX() {
// Define string variables.
_bstr_t strCmdSQL("Select title ,type, pubdate FROM titles ORDER BY title");
_bstr_t strSQL("SELECT title_ID AS TitleID, title AS Title, "
"publishers.pub_id AS PubID, pub_name AS PubName "
"FROM publishers INNER JOIN titles "
"ON publishers.pub_id = titles.pub_id "
"ORDER BY Title");
_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");
try {
// Open a connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open (strCnn, "", "", adConnectUnspecified);
if (pRstTitles)
if (pRstTitles->State == adStateOpen)
pRstTitles->Close();
if (pRstPublishers)
if (pRstPublishers->State == adStateOpen)
pRstPublishers->Close();
if (pRstPublishersDirect)
if (pRstPublishersDirect->State == adStateOpen)
pRstPublishersDirect->Close();
if (pRstTitlesPublishers)
if (pRstTitlesPublishers->State == adStateOpen)
pRstTitlesPublishers->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}
if ( (pConnection->Errors->Count) > 0 ) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
Recordset Object (ADO )
Source Property (ADO Recordset)
CacheSize Property Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the CacheSize property to show the difference in performance for an operation performed with
and without a 30-record cache.
// CacheSize_Property_Sample.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
#include <winbase.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void CacheSizeX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
CacheSizeX();
::CoUninitialize();
}
void CacheSizeX() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace
_RecordsetPtr pRstRoySched = NULL;
try {
// Open the RoySched table.
TESTHR(pRstRoySched.CreateInstance(__uuidof(Recordset)));
pRstRoySched->Open("roysched", strCnn, adOpenForwardOnly, adLockReadOnly, adCmdTable);
// Enumerate the Recordset object twice and record the elapsed time.
sngStart = GetTickCount();
while ( !(pRstRoySched->EndOfFile) ) {
// Execute a simple operation for the performance test.
strTemp = pRstRoySched->Fields->Item["title_id"]->Value;
pRstRoySched->MoveNext();
}
}
}
sngEnd = GetTickCount();
sngNoCache = (float)(sngEnd - sngStart) / (float)1000;
sngStart = GetTickCount();
// Enumerate the Recordset object twice and record the elapsed time.
for ( intLoop = 1 ; intLoop < 2 ; intLoop++ ) {
pRstRoySched->MoveFirst();
while ( !(pRstRoySched->EndOfFile) ) {
// Execute a simple operation for the performance test.
strTemp = pRstRoySched->Fields->Item["title_id"]->Value;
pRstRoySched->MoveNext();
}
}
sngEnd = GetTickCount();
sngCache = (float)(sngEnd - sngStart) / (float)1000;
if ( (pConnection->Errors->Count) > 0 ) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s", pErr->Number, pErr->Description);
}
}
}
See Also
CacheSize Property (ADO )
Recordset Object (ADO )
Cancel Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
object.Cancel
Remarks
Use the Cancel method to terminate execution of an asynchronous method call: that is, a method invoked with
the adAsyncConnect, adAsyncExecute, or adAsyncFetch option.
The following table shows what task is terminated when you use the Cancel method on a particular type of
object.
Command Execute
Recordset Open
Stream Open
Applies To
See Also
Cancel Method Example (VB )
Cancel Method Example (VBScript)
Cancel Method Example (VC++)
Cancel Method (RDS )
CancelBatch Method (ADO )
CancelUpdate Method (ADO )
CancelUpdate Method (RDS )
Execute Method (ADO Command)
Execute Method (ADO Connection)
Open Method (ADO Connection)
Open Method (ADO Recordset)
FieldStatusEnum
10/1/2018 • 3 minutes to read • Edit Online
ADO/WFC Equivalent
These constants do not have ADO/WFC equivalents.
Applies To
Status Property (ADO Field)
Parameter Object
10/1/2018 • 2 minutes to read • Edit Online
Represents a parameter or argument associated with a Command object based on a parameterized query or
stored procedure.
Remarks
Many providers support parameterized commands. These are commands in which the desired action is
defined once, but variables (or parameters) are used to alter some details of the command. For example, an
SQL SELECT statement could use a parameter to define the matching criteria of a WHERE clause, and
another to define the column name for a SORT BY clause.
Parameter objects represent parameters associated with parameterized queries, or the in/out arguments
and the return values of stored procedures. Depending on the functionality of the provider, some collections,
methods, or properties of a Parameter object may not be available.
With the collections, methods, and properties of a Parameter object, you can do the following:
Set or return the name of a parameter with the Name property.
Set or return the value of a parameter with the Value property. Value is the default property of the
Parameter object.
Set or return parameter characteristics with the Attributes, Direction, Precision, NumericScale, Size,
and Type properties.
Pass long binary or character data to a parameter with the AppendChunk method.
Access provider-specific attributes by using the Properties collection.
If you know the names and properties of the parameters associated with the stored procedure or
parameterized query you want to call, you can use the CreateParameter method to create Parameter objects
with the appropriate property settings and use the Append method to add them to the Parameters collection.
This lets you set and return parameter values without having to call the Refresh method on the Parameters
collection to retrieve the parameter information from the provider, a potentially resource-intensive operation.
The Parameter object is not safe for scripting.
This section contains the following topic.
Parameter Object Properties, Methods, and Events
See Also
Command Object (ADO )
CreateParameter Method (ADO )
Parameters Collection (ADO )
Properties Collection (ADO )
ADCPROP_AUTORECALC_ENUM
10/1/2018 • 2 minutes to read • Edit Online
Specifies when the MSDataShape provider re-calculates aggregate and calculated columns in a hierarchical
Recordset.
These constants are only used with the MSDataShape provider and the Recordset "Auto Recalc" dynamic
property, which is referenced in the ADO Dynamic Property Index and documented in the Microsoft Cursor
Service for OLE DB or Microsoft Data Shaping Service for OLE DB documentation.
ADO/WFC Equivalent
These constants do not have ADO/WFC equivalents.
Stream (ADO for Visual C++ Syntax)
10/1/2018 • 2 minutes to read • Edit Online
Methods
Cancel(void)
Close(void)
CopyTo(_ADOStream *DestStream, LONG CharNumber = -1)
Flush(void)
LoadFromFile(BSTR FileName)
Open(VARIANT Source, ConnectModeEnum Mode, StreamOpenOptionsEnum Options, BSTR UserName, BSTR Password)
Read(long NumBytes, VARIANT *pVal)
ReadText(long NumChars, BSTR *pbstr)
SaveToFile(BSTR FileName, SaveOptionsEnum Options = adSaveCreateNotExist)
SetEOS(void)
SkipLine(void)
Write(VARIANT Buffer)
WriteText(BSTR Data, StreamWriteEnum Options = adWriteChar)
Properties
get_Charset(BSTR *pbstrCharset)
put_Charset(BSTR Charset)
get_EOS(VARIANT_BOOL *pEOS)
get_LineSeparator(LineSeparatorEnum *pLS)
put_LineSeparator(LineSeparatorEnum LineSeparator)
get_Mode(ConnectModeEnum *pMode)
put_Mode(ConnectModeEnum Mode)
get_Position(LONG *pPos)
put_Position(LONG Position)
get_Size(LONG *pSize)
get_State(ObjectStateEnum *pState)
get_Type(StreamTypeEnum *pType)
put_Type(StreamTypeEnum Type)
See Also
Stream Object (ADO )
Save and Open Methods Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
These three examples demonstrate how the Save and Open methods can be used together.
Assume that you are going on a business trip and want to take along a table from a database. Before you go, you
access the data as a Recordset and save it in a transportable form. When you arrive at your destination, you access
the Recordset as a local, disconnected Recordset. You make changes to the Recordset, and then save it again.
Finally, when you return home, you connect to the database again and update it with the changes you made on the
road.
First, access and save the Authors table.
'BeginSaveVB
' clean up
rstAuthors.Close
Cnxn.Close
Set rstAuthors = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
'clean up
If Not rstAuthors Is Nothing Then
If rstAuthors.State = adStateOpen Then rstAuthors.Close
End If
Set rstAuthors = Nothing
At this point, you have arrived at your destination. You will access the Authors table as a local, disconnected
Recordset. You must have the MSPersist provider on the computer that you are using to access the saved file,
a:\Pubs.xml.
Finally, you return home. Now update the database with your changes.
Remarks
This property can be used to identify the page number on which the current record is located. It uses the
PageSize property to logically divide the total rowset count of the Recordset object into a series of pages, each
of which has the number of records equal to PageSize (except for the last page, which may have fewer records).
The provider must support the appropriate functionality for this property to be available.
When getting or setting the AbsolutePage property, ADO uses the AbsolutePosition property and the
PageSize property together as follows:
To get the AbsolutePage, ADO first retrieves the AbsolutePosition, and then divides it by the
PageSize.
To set the AbsolutePage, ADO moves the AbsolutePosition as follows: it multiplies the PageSize by
the new AbsolutePage value and then adds 1 to the value. As a result, the current position in the
Recordset after successfully setting AbsolutePage is the first record in that page.
Like the AbsolutePosition property, AbsolutePage is 1-based and equals 1 when the current record is the
first record in the Recordset. Set this property to move to the first record of a particular page. Obtain the total
number of pages from the PageCount property.
Applies To
Recordset Object (ADO )
See Also
AbsolutePage, PageCount, and PageSize Properties Example (VB )
AbsolutePage, PageCount, and PageSize Properties Example (VC++)
AbsolutePosition Property (ADO )
PageCount Property (ADO )
PageSize Property (ADO )
WillExecute Event (ADO)
1/14/2019 • 2 minutes to read • Edit Online
The WillExecute event is called just before a pending command executes on a connection.
Syntax
WillExecute Source, CursorType, LockType, Options, adStatus, pCommand, pRecordset, pConnection
Parameters
Source
A String that contains an SQL command or a stored procedure name.
CursorType
A CursorTypeEnum that contains the type of cursor for the Recordset that will be opened. With this parameter,
you can change the cursor to any type during a RecordsetOpen Method (ADO Recordset) operation. CursorType
will be ignored for any other operation.
LockType
A LockTypeEnum that contains the lock type for the Recordset that will be opened. With this parameter, you can
change the lock to any type during a RecordsetOpen operation. LockType will be ignored for any other operation.
Options
A Long value that indicates options that can be used to execute the command or open the Recordset.
adStatus
An EventStatusEnum status value that may be adStatusCantDeny or adStatusOK when this event is called. If it
is adStatusCantDeny, this event may not request cancellation of the pending operation.
pCommand
The Command Object (ADO ) object for which this event notification applies.
pRecordset
The Recordset Object (ADO ) object for which this event notification applies.
pConnection
The Connection Object (ADO ) object for which this event notification applies.
Remarks
A WillExecute event may occur due to a Connection. Execute Method (ADO Connection), Execute Method (ADO
Command), or Open Method (ADO Recordset) method The pConnection parameter should always contain a valid
reference to a Connection object. If the event is due to Connection.Execute, the pRecordset and pCommand
parameters are set to Nothing. If the event is due to Recordset.Open, the pRecordset parameter will reference
the Recordset object and the pCommand parameter is set to Nothing. If the event is due to
Command.Execute, the pCommand parameter will reference the Command object and the pRecordset
parameter is set to Nothing.
WillExecute allows you to examine and modify the pending execution parameters. This event may return a
request that the pending command be canceled.
NOTE
If the original source for a Command is a stream specified by the CommandStream Property (ADO) property, assigning a
new string to the WillExecuteSource parameter changes the source of the Command. The CommandStream property will
be cleared and the CommandText Property (ADO) property will be updated with the new source. The original stream
specified by CommandStream will be released and cannot be accessed.
If the dialect of the new source string differs from the original setting of the Dialect Property property (which
corresponded to the CommandStream ), the correct dialect must be specified by setting the Dialect property of
the command object referenced by pCommand.
See Also
ADO Events Model Example (VC++)
ADO Event Handler Summary
Connection Object (ADO )
ConnectionEvents (Visual C++ Syntax Index with
#import)
10/1/2018 • 2 minutes to read • Edit Online
Events
HRESULT InfoMessage( struct Error * pError, enum
EventStatusEnum * adStatus, struct _Connection * pConnection );
This example uses the AddNew method to create a new record with the specified name.
Use the following example in an Active Server Page (ASP ). Use Find to locate the file Adovbs.inc and place it in the
directory you plan to use. Cut and paste the following code to Notepad or another text editor, and save it as
AddNewVBS.asp. You can view the result in any client browser.
To exercise the example, add a new record in the HTML form. Click Add New. See the Delete Method Example to
remove unwanted records.
rsCustomers.ActiveConnection = Cnxn
rsCustomers.CursorLocation = adUseClient
rsCustomers.CursorType = adOpenKeyset
rsCustomers.LockType = adLockOptimistic
rsCustomers.Source = strSQLCustomers
rsCustomers.Open
<HR>
<!--
Form to enter new record posts variables
back to this page
-->
<FORM Method=post Action="AddNewVbs.asp" Name=Form>
<TABLE>
<TR>
<TD>Company ID:</TD>
<TD><INPUT Size="5" Name="CompanyID" maxLength=5 ></TD>
</TR>
<TR>
<TD>Company Name:</TD>
<TD><INPUT Size="50" Name="CompanyName" ></TD>
</TR>
<TR>
<TD>Contact First Name:</TD>
<TD><INPUT Size="50" Name="FirstName" ></TD>
</TR>
<TR>
<TD>Contact Last Name:</TD>
<TD><INPUT Size="50" Name="LastName" ></TD>
</TR>
<TR>
<TD>Contact Phone:</TD>
<TD><INPUT Size="50" Name="PhoneNumber" ></TD>
</TR>
<TR>
<TD>City:</TD>
<TD><INPUT Size="50" Name="City" ></TD>
</TR>
<TR>
<TD>State / Province:</TD>
<TD><INPUT Size="5" Name="State" ></TD>
</TR>
<TR>
<TD Align="right"><INPUT Type="submit" Value="Add New"></TD>
<TD Align="left"><INPUT Type="reset" Value="Reset Form"></TD>
</TR>
</TABLE>
</FORM>
<%
' Show connection.
Response.Write("Following is the connection string: <br><br>")
Response.Write(Cnxn)
See Also
AddNew Method (ADO )
Recordset Object (ADO )
CancelBatch Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
recordset.CancelBatchAffectRecords
Parameters
AffectRecords
Optional. An AffectEnum value that indicates how many records the CancelBatch method will affect.
Remarks
Use the CancelBatch method to cancel any pending updates in a Recordset in batch update mode. If the
Recordset is in immediate update mode, calling CancelBatch without adAffectCurrent generates an error.
If you are editing the current record or are adding a new record when you call CancelBatch, ADO first calls the
CancelUpdate method to cancel any cached changes. After that, all pending changes in the Recordset are
canceled.
The current record may be indeterminable after a CancelBatch call, especially if you were in the process of
adding a new record. For this reason, it is prudent to set the current record position to a known location in the
Recordset after the CancelBatch call. For example, call the MoveFirst method.
If the attempt to cancel the pending updates fails because of a conflict with the underlying data (for example, if a
record has been deleted by another user), the provider returns warnings to the Errors collection but does not
halt program execution. A run-time error occurs only if there are conflicts on all the requested records. Use the
Filter property ( adFilterAffectedRecords) and the Status property to locate records with conflicts.
Applies To
Recordset Object (ADO )
See Also
UpdateBatch and CancelBatch Methods Example (VB )
UpdateBatch and CancelBatch Methods Example (VC++)
Cancel Method (ADO )
Cancel Method (RDS )
CancelUpdate Method (ADO )
CancelUpdate Method (RDS )
Clear Method (ADO )
LockType Property (ADO )
UpdateBatch Method
Record Object (ADO)
11/28/2018 • 3 minutes to read • Edit Online
Represents a row from a Recordset or the data provider, or an object returned by a semi-structured data
provider, such as a file or directory.
Remarks
A Record object represents one row of data, and has some conceptual similarities with a one-row
Recordset. Depending on the capabilities of your provider, Record objects may be returned directly from
your provider instead of a one-row Recordset, for example when an SQL query that selects only one row
is executed. Or, a Record object can be obtained directly from a Recordset object. Or, a Record can be
returned directly from a provider to semi-structured data, such as the Microsoft Exchange OLE DB
provider.
You can view the fields associated with the Record object by way of the Fields collection on the Record
object. ADO allows object-valued columns including Recordset, SafeArray, and scalar values in the
Fields collection of Record objects.
If the Record object represents a row in a Recordset, it is possible to return to that original Recordset
with the Source property.
The Record object can also be used by semi-structured data providers such as the Microsoft OLE DB
Provider for Internet Publishing, to model tree-structured namespaces. Each node in the tree is a Record
object with associated columns. The columns can represent the attributes of that node and other relevant
information. The Record object can represent both a leaf node and a non-leaf node in the tree structure.
Non-leaf nodes have other nodes as their contents, but leaf nodes do not have such contents. Leaf nodes
typically contain binary streams of data and non-leaf nodes may also have a default binary stream
associated with them. Properties on the Record object identify the type of node.
The Record object also represents an alternative way for navigating hierarchically organized data. A
Record object may be created to represent the root of a specific sub-tree in a large tree structure and new
Record objects may be opened to represent child nodes.
A resource (for example, a file or directory) can be uniquely identified by an absolute URL. A Connection
object is implicitly created and set to the Record object when the Record is opened by using an absolute
URL. A Connection object may explicitly be set to the Record object via the ActiveConnection property.
The files and directories that can be accessed by using the Connection object define the context in which
Record operations may occur.
Data modification and navigation methods on the Record object also accept a relative URL, which locates
a resource using an absolute URL or the Connection object context as a starting point.
NOTE
URLs using the http scheme will automatically invoke the Microsoft OLE DB Provider for Internet Publishing. For
more information, see Absolute and Relative URLs.
A Connection object is associated with each Record object. Therefore, Record object operations can be
part of a transaction by invoking Connection object transaction methods.
The Record object does not support ADO events, and therefore will not respond to notifications.
With the methods and properties of a Record object, you can do the following:
Set or return the associated Connection object with the ActiveConnection property.
Indicate access permissions with the Mode property.
Return the URL of the directory, if any, that contains the resource represented by the Record with
the ParentURL property.
Indicate the absolute URL, relative URL, or Recordset from which the Record is derived with the
Source property.
Indicate the current status of the Record with the State property.
Indicate the type of Record - simple, collection, or structured document - with the
RecordTypeproperty.
Stop execution of an asynchronous operation with the Cancel method.
Disassociate the Record from a data source with the Close method.
Copy the file or directory represented by a Record to another location with the CopyRecord
method.
Delete the file, or directory and subdirectories, represented by a Record with the DeleteRecord
method.
Open a Recordset that contains rows that represent the subdirectories and files of the entity
represented by the Record with the GetChildren method.
Move (rename) the file, or directory and subdirectories, represented by a Record to another
location with the MoveRecord method.
Associate the Record with an existing data source, or create a new file or directory with the Open
method.
The Record object is safe for scripting.
This section contains the following topic.
Record Object Properties, Methods, and Events
See Also
Fields Collection (ADO )
Properties Collection (ADO )
Records and Streams
Recordset Object (ADO )
Version Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Return Value
Returns a String value that indicates the version.
Remarks
Use the Version property to return the version number of the ADO implementation.
The version of the provider will be available as a dynamic property in the Properties collection.
Applies To
Connection Object (ADO )
See Also
Version Property Example (VB )
Version Property Example (VC++)
ActiveConnection, CommandText,
CommandTimeout, CommandType, Size, and
Direction Properties Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction
properties to execute a stored procedure.
'BeginActiveConnectionVB
cmdByRoyalty.Parameters.Append prmByRoyalty
' Open the Authors Table to get author names for display
Set rstAuthors = New ADODB.Recordset
strSQLAuthors = "Authors"
' Print the recordset and add author names from Table
Debug.Print "Authors with " & intRoyalty & _
" percent royalty"
Do Until rstByRoyalty.EOF
strAuthorID = rstByRoyalty!au_id
Debug.Print , rstByRoyalty!au_id & ", ";
rstAuthors.Filter = "au_id = '" & strAuthorID & "'"
Debug.Print rstAuthors!au_fname & " " & _
rstAuthors!au_lname
rstByRoyalty.MoveNext
Loop
' clean up
rstAuthors.Close
rstByRoyalty.Close
Cnxn.Close
Set rstAuthors = Nothing
Set rstByRoyalty = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstAuthors Is Nothing Then
If rstAuthors.State = adStateOpen Then rstAuthors.Close
End If
Set rstAuthors = Nothing
See Also
ActiveCommand Property (ADO )
Command Object (ADO )
CommandText Property (ADO )
CommandTimeout Property (ADO )
CommandType Property (ADO )
Connection Object (ADO )
Direction Property
Parameter Object
Record Object (ADO )
Recordset Object (ADO )
Size Property (ADO Parameter)
Record Object Properties, Methods, and Events
10/1/2018 • 2 minutes to read • Edit Online
Properties/Collections
ActiveConnection Property
Fields Collection
Mode Property
ParentURL Property
Properties Collection
RecordType Property
Source Property (ADO Record)
State Property
Methods
Cancel Method
Close Method
CopyRecord Method
DeleteRecord Method
GetChildren Method
MoveRecord Method
Open Method (ADO Record)
Events
None.
See Also
Record Object (ADO )
Position Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
The current position can be moved to a point after the end of the stream. If you specify the current position
beyond the end of the stream, the Size of the Stream object will be increased accordingly. Any new bytes added
in this way will be null.
NOTE
Position always measures bytes. For text streams using multibyte character sets, multiply the position by the character size
to determine the character number. For example, for a two-byte character set, the first character is at position 0, the
second character at position 2, the third character at position 4, and so on.
NOTE
Negative values cannot be used to change the current position in a Stream. Only positive numbers can be used for
Position.
NOTE
For read-only Stream objects, ADO will not return an error if Position is set to a value greater than the Size of the
Stream. This does not change the size of the Stream, or alter the Stream contents in any way. However, doing this
should be avoided because it results in a meaningless Positionvalue.
Applies To
Stream Object (ADO )
See Also
Charset Property (ADO )
Count Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Return Value
Returns a Long value.
Remarks
Use the Count property to determine how many objects are in a given collection.
Because numbering for members of a collection begins with zero, you should always code loops starting with
the zero member and ending with the value of the Count property minus 1. If you are using Microsoft Visual
Basic and want to loop through the members of a collection without checking the Count property, use the For
Each...Next command.
If the Count property is zero, there are no objects in the collection.
Applies To
Axes Collection (ADO MD) Columns Collection (ADOX) CubeDefs Collection (ADO MD)
Dimensions Collection (ADO MD) Errors Collection (ADO) Fields Collection (ADO)
Groups Collection (ADOX) Hierarchies Collection (ADO MD) Indexes Collection (ADOX)
Keys Collection (ADOX) Levels Collection (ADO MD) Members Collection (ADO MD)
Parameters Collection (ADO) Positions Collection (ADO MD) Procedures Collection (ADOX)
See Also
Count Property Example (VB )
Count Property Example (VC++)
Refresh Method (ADO )
WillConnect Event (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
WillConnect ConnectionString, UserID, Password, Options, adStatus, pConnection
Parameters
ConnectionString
A String that contains connection information for the pending connection.
UserID
A String that contains a user name for the pending connection.
Password
A String that contains a password for the pending connection.
Options
A Long value that indicates how the provider should evaluate the ConnectionString. Your only option is
adAsyncOpen.
adStatus
An EventStatusEnum status value.
When this event is called, this parameter is set to adStatusOK by default. It is set to adStatusCantDeny if the
event cannot request cancellation of the pending operation.
Before this event returns, set this parameter to adStatusUnwantedEvent to prevent subsequent notifications.
Set this parameter to adStatusCancel to request the connection operation that caused cancellation of this
notification.
pConnection
The Connection object for which this event notification applies. Changes to the parameters of the Connection by
the WillConnect event handler will have no effect on the Connection.
Remarks
When WillConnect is called, the ConnectionString, UserID, Password, and Options parameters are set to the
values established by the operation that caused this event (the pending connection), and can be changed before
the event returns. WillConnect may return a request that the pending connection be canceled.
When this event is canceled, ConnectComplete will be called with its adStatus parameter set to
adStatusErrorsOccurred.
See Also
ADO Events Model Example (VC++)
ADO Event Handler Summary
Provider and DefaultDatabase Properties Example
(VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Provider property by opening three Connection objects using different providers.
It also uses the DefaultDatabase property to set the default database for the Microsoft ODBC Provider.
// Provider_and_DefaultDatabase_Properties.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
// Function declarations
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void ProviderX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
ProviderX();
::CoUninitialize();
}
void ProviderX() {
HRESULT hr = S_OK;
// Define ADO object pointers. Initialize pointers on define. These are in the ADODB:: namespace.
_ConnectionPtr pConnection1 = NULL;
_ConnectionPtr pConnection2 = NULL;
_ConnectionPtr pConnection3 = NULL;
try {
// Open a Connection using the Microsoft ODBC provider.
TESTHR(pConnection1.CreateInstance(__uuidof(Connection)));
pConnection1->ConnectionString = "DSN=Data;user id='MyUserId';password='MyPassword';";
pConnection1->Open("", "", "", adConnectUnspecified);
pConnection1->DefaultDatabase = "pubs";
// Display the provider
printf("\n\nConnection1 provider: %s \n\n", (LPCSTR)pConnection1->Provider);
if (pConnection3)
PrintProviderError(pConnection3);
PrintComError(e);
}
if (pConnection1)
if (pConnection1->State == adStateOpen)
pConnection1->Close();
if (pConnection2)
if (pConnection2->State == adStateOpen)
pConnection2->Close();
if (pConnection3)
if (pConnection3->State == adStateOpen)
pConnection3->Close();
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
See Also
Connection Object (ADO )
DefaultDatabase Property
Provider Property (ADO )
Requery Method
10/1/2018 • 2 minutes to read • Edit Online
Updates the data in a Recordset object by re-executing the query on which the object is based.
Syntax
recordset.Requery Options
Parameters
Options
Optional. A bitmask that contains ExecuteOptionEnum and CommandTypeEnum values affecting this
operation.
NOTE
If Options is set to adAsyncExecute, this operation will execute asynchronously and a RecordsetChangeComplete event
will be issued when it concludes. The ExecuteOpenEnum values of adExecuteNoRecords or adExecuteStream should
not be used with Requery.
Remarks
Use the Requery method to refresh the entire contents of a Recordset object from the data source by
reissuing the original command and retrieving the data a second time. Calling this method is equivalent to
calling the Close and Open methods in succession. If you are editing the current record or adding a new record,
an error occurs.
While the Recordset object is open, the properties that define the nature of the cursor ( CursorType, LockType,
MaxRecords, and so forth) are read-only. Thus, the Requery method can only refresh the current cursor. To
change any of the cursor properties and view the results, you must use the Close method so that the properties
become read/write again. You can then change the property settings and call the Open method to reopen the
cursor.
Applies To
Recordset Object (ADO )
See Also
Execute, Requery, and Clear Methods Example (VB )
Execute, Requery, and Clear Methods Example (VBScript)
Execute, Requery, and Clear Methods Example (VC++)
CommandText Property (ADO )
ADO Dynamic Properties
10/1/2018 • 2 minutes to read • Edit Online
Dynamic properties can be added to the Properties collections of the Connection, Command, or Recordset
objects. The source for these properties is either a data provider, such as the OLE DB Provider for SQL Server, or
a service provider, such as the Microsoft Cursor Service for OLE DB. Refer to the appropriate data provider or
service provider documentation for more information about a specific dynamic property.
The ADO Dynamic Property Index provides a cross-reference between the ADO and OLE DB names for each
standard OLE DB provider dynamic property.
The following dynamic properties are especially interesting, and are also documented in the sources that were
mentioned earlier. Special functionality with ADO is documented in the ADO help topics in the following list.
Unique Table, Unique Schema, Unique Catalog Unique Table Specifies the name of the base table upon
which updates, insertions, and deletions are allowed.
See Also
ADO API Reference
ADO Collections
ADO Enumerated Constants
Appendix B: ADO Errors
ADO Events
ADO Methods
ADO Object Model
ADO Objects and Interfaces
ADO Properties
WillChangeRecordset and
RecordsetChangeComplete Events (ADO)
10/1/2018 • 2 minutes to read • Edit Online
The WillChangeRecordset event is called before a pending operation changes the Recordset. The
RecordsetChangeComplete event is called after the Recordset has changed.
Syntax
WillChangeRecordset adReason, adStatus, pRecordset
RecordsetChangeComplete adReason, pError, adStatus, pRecordset
Parameters
adReason
An EventReasonEnum value that specifies the reason for this event. Its value can be adRsnRequery,
adRsnResynch, adRsnClose, adRsnOpen.
adStatus
An EventStatusEnum status value.
When WillChangeRecordset is called, this parameter is set to adStatusOK if the operation that caused the
event was successful. It is set to adStatusCantDeny if this event cannot request cancellation of the pending
operation.
When RecordsetChangeComplete is called, this parameter is set to adStatusOK if the operation that caused
the event was successful, adStatusErrorsOccurred if the operation failed, or adStatusCancel if the operation
associated with the previously accepted WillChangeRecordset event has been canceled.
Before WillChangeRecordset returns, set this parameter to adStatusCancel to request cancellation of the
pending operation or set this parameter to adStatusUnwantedEvent to prevent subsequent notifications.
Before WillChangeRecordset or RecordsetChangeComplete returns, set this parameter to
adStatusUnwantedEvent to prevent subsequent notifications.
pError
An Error object. It describes the error that occurred if the value of adStatus is adStatusErrorsOccurred;
otherwise it is not set.
pRecordset
A Recordset object. The Recordset for which this event occurred.
Remarks
A WillChangeRecordset or RecordsetChangeComplete event may occur because of the Recordset Requery
or Open methods.
If the provider does not support bookmarks, a RecordsetChange event notification occurs every time that new
rows are retrieved from the provider. The frequency of this event depends on the RecordsetCacheSize property.
You must set the adStatus parameter to adStatusUnwantedEvent for each possible adReason value to
completely stop event notification for any event that includes an adReason parameter.
See Also
ADO Events Model Example (VC++)
ADO Event Handler Summary
Direction Property
10/1/2018 • 2 minutes to read • Edit Online
Indicates whether the parameter represents an input parameter, an output parameter, an input and an output
parameter, or if the parameter is the return value from a stored procedure.
Remarks
Use the Direction property to specify how a parameter is passed to or from a procedure. The Direction
property is read/write; this allows you to work with providers that don't return this information or to set this
information when you don't want ADO to make an extra call to the provider to retrieve parameter information.
Not all providers can determine the direction of parameters in their stored procedures. In these cases, you must
set the Direction property before you execute the query.
Applies To
Parameter Object
See Also
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(VB )
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(VC++)
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(JScript)
BeginTrans, CommitTrans, and RollbackTrans
Methods (ADO)
10/1/2018 • 2 minutes to read • Edit Online
These transaction methods manage transaction processing within a Connection object as follows:
BeginTrans Begins a new transaction.
CommitTrans Saves any changes and ends the current transaction. It may also start a new transaction.
RollbackTrans Cancels any changes made during the current transaction and ends the transaction. It
may also start a new transaction.
Syntax
level = object.BeginTrans()
object.BeginTrans
object.CommitTrans
object.RollbackTrans
Return Value
BeginTrans can be called as a function that returns a Long variable indicating the nesting level of the
transaction.
Parameters
object
A Connection object.
Connection
Use these methods with a Connection object when you want to save or cancel a series of changes made to
the source data as a single unit. For example, to transfer money between accounts, you subtract an amount
from one and add the same amount to the other. If either update fails, the accounts no longer balance. Making
these changes within an open transaction ensures that either all or none of the changes go through.
NOTE
Not all providers support transactions. Verify that the provider-defined property "Transaction DDL" appears in the
Connection object's Properties collection, indicating that the provider supports transactions. If the provider does not
support transactions, calling one of these methods will return an error.
After you call the BeginTrans method, the provider will no longer instantaneously commit changes you make
until you call CommitTrans or RollbackTrans to end the transaction.
For providers that support nested transactions, calling the BeginTrans method within an open transaction
starts a new, nested transaction. The return value indicates the level of nesting: a return value of "1" indicates
you have opened a top-level transaction (that is, the transaction is not nested within another transaction), "2"
indicates that you have opened a second-level transaction (a transaction nested within a top-level transaction),
and so forth. Calling CommitTrans or RollbackTrans affects only the most recently opened transaction; you
must close or roll back the current transaction before you can resolve any higher-level transactions.
Calling the CommitTrans method saves changes made within an open transaction on the connection and
ends the transaction. Calling the RollbackTrans method reverses any changes made within an open
transaction and ends the transaction. Calling either method when there is no open transaction generates an
error.
Depending on the Connection object's Attributes property, calling either the CommitTrans or
RollbackTrans methods may automatically start a new transaction. If the Attributes property is set to
adXactCommitRetaining, the provider automatically starts a new transaction after a CommitTrans call. If
the Attributes property is set to adXactAbortRetaining, the provider automatically starts a new transaction
after a RollbackTrans call.
Applies To
Connection Object (ADO )
See Also
BeginTrans, CommitTrans, and RollbackTrans Methods Example (VB )
BeginTrans, CommitTrans, and RollbackTrans Methods Example (VC++)
Attributes Property (ADO )
AddNew Method Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the AddNew method to create a new record with the specified name.
'BeginAddNewVB
rstEmployees.AddNew
rstEmployees!firstname = strFirstName
rstEmployees!LastName = strLastName
rstEmployees.Update
blnRecordAdded = True
Else
MsgBox "Please enter a first name and last name."
End If
' clean up
rstEmployees.Close
rstEmployees.Close
Cnxn.Close
Set rstEmployees = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstEmployees Is Nothing Then
If rstEmployees.State = adStateOpen Then rstEmployees.Close
End If
Set rstEmployees = Nothing
See Also
AddNew Method (ADO )
Recordset Object (ADO )
ResyncEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.Resync.ALLVALUES
AdoEnums.Resync.UNDERLYINGVALUES
Applies To
Resync Method
Resync Method Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates using the Resync method to refresh data in a static recordset.
// Resync_Method_Sample.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void ResyncX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
ResyncX();
::CoUninitialize();
}
void ResyncX() {
// Define string variables.
_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");
try {
// Open recordset for titles table.
TESTHR(pRstTitles.CreateInstance(__uuidof(Recordset)));
pRstTitles->CursorLocation = adUseClient;
pRstTitles->CursorType = adOpenStatic;
pRstTitles->LockType = adLockBatchOptimistic;
pRstTitles->Open ("titles", strCnn, adOpenStatic, adLockBatchOptimistic, adCmdTable);
printf("Title - %s\n\n",
(LPSTR)(_bstr_t) pRstTitles->Fields->GetItem("title")->Value);
printf("Type - %s\n\n",
(LPSTR)(_bstr_t) pRstTitles->Fields->GetItem("type")->Value);
printf("Title - %s\n\n",
printf("Title - %s\n\n",
(LPSTR)(_bstr_t) pRstTitles->Fields->GetItem("title")->Value);
printf("Type - %s\n\n",
(LPSTR)(_bstr_t) pRstTitles->Fields->GetItem("type")->Value);
}
catch (_com_error &e) {
// Display errors, if any. Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstTitles->GetActiveConnection();
if (pRstTitles)
if (pRstTitles->State == adStateOpen) {
pRstTitles->CancelBatch(adAffectAll);
pRstTitles->Close();
}
}
if ( (pConnection->Errors->Count) > 0 ) {
long nCount = pConnection->Errors->Count;
See Also
Resync Method
GetRows Method Example (JScript)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the GetRows method to retrieve all rows of the Custiomers table from a Recordset and to fill an
array with the resulting data. The GetRows method will return fewer than the desired number of rows in two cases:
either if EOF has been reached, or if GetRows tried to retrieve a record that was deleted by another user. The
function returns False only if the second case occurs. Cut and paste the following code to Notepad or another text
editor, and save it as GetRowsJS.asp.
<html>
<head>
<title>ADO Recordset.GetRows Example (JScript)</title>
<style>
<!--
BODY {
font-family: 'Verdana','Arial','Helvetica',sans-serif;
BACKGROUND-COLOR:white;
COLOR:black;
}
.thead {
background-color: #008080;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
color: white;
}
.thead2 {
background-color: #800000;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
color: white;
}
.tbody {
text-align: center;
background-color: #f7efde;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
}
-->
</style>
</head>
<body bgcolor="white">
try
{
connTemp.Open(Connect);
var rsTemp = Server.CreateObject("ADODB.Recordset");
rsTemp.ActiveConnection = connTemp;
rsTemp.CursorLocation = adUseClient;
rsTemp.CursorType = adOpenKeyset;
rsTemp.LockType = adLockOptimistic;
rsTemp.Open(mySQL);
rsTemp.MoveFirst();
if (rsTemp.RecordCount == 0)
{
Response.Write("No records matched ");
Response.Write (mySQL & "So cannot make table...");
connTemp.Close();
Response.End();
} else
{
Response.Write('<table width="100%" border="2">');
Response.Write('<tr class="thead2">');
Response.Write("</tr>");
var col = 1;
var maxCols = rsTemp.Fields.Count;
</body>
</html>
<!-- EndGetRowsJS -->
See Also
GetRows Method (ADO )
Recordset Object (ADO )
LockTypeEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.LockType.BATCHOPTIMISTIC
AdoEnums.LockType.OPTIMISTIC
AdoEnums.LockType.PESSIMISTIC
AdoEnums.LockType.READONLY
AdoEnums.LockType.UNSPECIFIED
Applies To
Syntax
Stream.Open Source, Mode , OpenOptions, UserName, Password
Parameters
Source
Optional. A Variant value that specifies the source of data for the Stream. Source may contain an absolute URL
string that points to an existing node in a well-known tree structure, such as an e-mail or file system. A URL
should be specified by using the URL keyword ("URL=scheme://server/folder"). Alternatively, Source may
contain a reference to an already open Record object, which opens the default stream associated with the
Record. If Source is not specified, a Stream is instantiated and opened, associated with no underlying source by
default. For more information about URL schemes and their associated providers, see Absolute and Relative
URLs.
Mode
Optional. A ConnectModeEnum value that specifies the access mode for the resultant Stream (for example,
read/write or read-only). Default value is adModeUnknown. See the Mode property for more information
about access modes. If Mode is not specified, it is inherited by the source object. For example, if the source
Record is opened in read-only mode, the Stream will also be opened in read-only mode by default.
OpenOptions
Optional. A StreamOpenOptionsEnum value. Default value is adOpenStreamUnspecified.
UserName
Optional. A String value that contains the user identification that, if it is needed, accesses the Stream object.
Password
Optional. A String value that contains the password that, if it is needed, accesses the Stream object.
Remarks
When a Record object is passed in as the source parameter, the UserID and Password parameters are not used
because access to the Record object is already available. Similarly, the Mode of the Record object is transferred
to the Stream object. When Source is not specified, the Stream opened contains no data and has a Size of zero
(0). To avoid losing any data that is written to this Stream when the Stream is closed, save the Stream with the
CopyTo or SaveToFile methods, or save it to another memory location.
An OpenOptions value of adOpenStreamFromRecord identifies the contents of the Source parameter to be an
already open Record object. The default behavior is to treat Source as a URL that points directly to a node in a
tree structure, such as a file. The default stream associated with that node is opened.
While the Stream is not open, it is possible to read all the read-only properties of the Stream. If a Stream is
opened asynchronously, all subsequent operations (other than checking the State and other read-only properties)
are blocked until the Open operation is completed.
In addition to the options that were discussed earlier, by not specifying Source, you can create an instance of a
Stream object in memory without associating it with an underlying source. You can dynamically add data to the
stream by writing binary or text data to the Stream with Write or WriteText, or by loading data from a file with
LoadFromFile.
Applies To
Stream Object (ADO )
See Also
Open Method (ADO Connection)
Open Method (ADO Record)
Open Method (ADO Recordset)
OpenSchema Method
SaveToFile Method
Unique Table, Unique Schema, Unique Catalog
Properties-Dynamic (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Enables you to closely control modifications to a particular base table in a Recordset that was formed by a JOIN
operation on multiple base tables.
Unique Table specifies the name of the base table upon which updates, insertions, and deletions are
allowed.
Unique Schema specifies the schema, or name of the owner of the table.
Unique Catalog specifies the catalog, or name of the database containing the table.
Remarks
The desired base table is uniquely identified by its catalog, schema, and table names. When the Unique Table
property is set, the values of the Unique Schema or Unique Catalog properties are used to find the base table.
It is intended, but not required, that either or both the Unique Schema and Unique Catalog properties be set
before the Unique Table property is set.
The primary key of the Unique Table is treated as the primary key of the entire Recordset. This is the key that is
used for any method requiring a primary key.
While Unique Table is set, the Delete method affects only the named table. The AddNew, Resync, Update, and
UpdateBatch methods affect any appropriate underlying base tables of the Recordset.
Unique Table must be specified before doing any custom resynchronizations. If Unique Table has not been
specified, the Resync Command property will have no effect.
A run-time error results if a unique base table cannot be found.
These dynamic properties are all appended to the Recordset object Properties collection when the
CursorLocation property is set to adUseClient.
Applies To
Recordset Object (ADO )
See Also
Recordset Object (ADO )
ADO Objects and Interfaces
10/1/2018 • 2 minutes to read • Edit Online
The relationships between these objects are represented in the ADO Object Model.
Each object can be contained in its corresponding collection. For example, an Error object can be contained in an
Errors collection. For more information, see ADO Collections or a specific collection topic.
IDSOShapeExtensions Interface Gets the underlying OLEDB Data Source object for the SHAPE
provider.
See Also
ADO API Reference
ADO Collections
ADO Dynamic Properties
ADO Enumerated Constants
Appendix B: ADO Errors
ADO Events
ADO Methods
ADO Object Model
ADO Properties
CompareBookmarks Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
result = recordset.CompareBookmarks(Bookmark1, Bookmark2)
Return Value
Returns a CompareEnum value that indicates the relative row position of two records represented by their
bookmarks.
Parameters
Bookmark1
The bookmark of the first row.
Bookmark2
The bookmark of the second row.
Remarks
The bookmarks must apply to the same Recordset object, or a Recordset object and its clone. You cannot reliably
compare bookmarks from different Recordset objects, even if they were created from the same source or
command. Nor can you compare bookmarks for a Recordset object whose underlying provider does not support
comparisons.
A bookmark uniquely identifies a row in a Recordset object. Use the Bookmark property of the current row to
obtain its bookmark.
Because the data type of a bookmark is specific to each provider, ADO exposes it as a Variant. For example, SQL
Server bookmarks are of type DBTYPE_R8 (Double). ADO would expose this type as a Variant with a subtype of
Double.
When comparing bookmarks, ADO does not attempt any type of coercion. The values are simply passed to the
provider where the comparison occurs. If the bookmarks passed to the CompareBookmarks method are stored
in variables of differing types, it can generate the following type mismatch error: "Arguments are of the wrong
type, are out of the acceptable range, or are in conflict with each other."
A bookmark that is not valid or incorrectly formed will cause an error.
Applies To
Recordset Object (ADO )
See Also
CompareBookmarks Method Example (VB )
CompareBookmarks Method Example (VC++)
Bookmark Property (ADO )
ADO for Visual C++ Syntax Index for COM
11/28/2018 • 2 minutes to read • Edit Online
This index is a cross-reference to the ADO Language Reference based on Microsoft Visual C++.
If you use the #import directive in your application, a header file will be generated that will enable you to use
syntax similar to Microsoft Visual Basic. Property names of the form get_PropertyName and put_PropertyName
can be treated as if they were declared simply as PropertyName. A property can then be treated like a data
member instead of a function.
All of the methods, properties, and events are functions that return an HRESULT, which you can test to determine
if the function executed successfully.
Method and property syntax in Visual C++ is listed for the following elements:
Collections
Command object
Connection object
Error object
Field object
Parameter object
Record object
Recordset object
Stream object
See Also
ADO for Visual C++ Syntax Index with #import
Microsoft ActiveX Data Objects (ADO )
Parameter (ADO - WFC Syntax)
11/28/2018 • 2 minutes to read • Edit Online
package com.ms.wfc.data
Constructor
public Parameter()
public Parameter(String name)
public Parameter(String name, int type)
public Parameter(String name, int type, int dir)
public Parameter(String name, int type, int dir, int size)
public Parameter(String name, int type, int dir, int size, Object value)
Methods
Properties
See Also
Parameter Object
Name Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the Name property to assign a name to or retrieve the name of a Command, Property, Field, or
Parameter object.
The value is read/write on a Command object and read-only on a Property object.
For a Field object, Name is normally read-only. However, for new Field objects that have been appended to the
Fields collection of a Record, Name is read/write only after the Value property for the Field has been specified
and the data provider has successfully added the new Field by calling the Update method of the Fields
collection.
For Parameter objects not yet appended to the Parameters collection, the Name property is read/write. For
appended Parameter objects and all other objects, the Name property is read-only. Names do not have to be
unique within a collection.
You can retrieve the Name property of an object by an ordinal reference, after which you can refer to the object
directly by name. For example, if rstMain.Properties(20).Name yields Updatability , you can subsequently refer
to this property as rstMain.Properties("Updatability") .
Applies To
See Also
Attributes and Name Properties Example (VB )
Attributes and Name Properties Example (VC++)
StreamReadEnum
10/1/2018 • 2 minutes to read • Edit Online
Specifies whether the whole stream or the next line should be read from a Stream object.
ADO/WFC Equivalent
These constants do not have ADO/WFC equivalents.
Applies To
Methods
Cancel(void)
CreateParameter(BSTR Name, DataTypeEnum Type, ParameterDirectionEnum Direction, long Size, VARIANT Value,
_ADOParameter **ppiprm)
Execute(VARIANT *RecordsAffected, VARIANT *Parameters, long Options, _ADORecordset **ppirs)
Properties
get_ActiveConnection(_ADOConnection **ppvObject)
put_ActiveConnection(VARIANT vConn)
putref_ActiveConnection(_ADOConnection *pCon)
get_CommandText(BSTR *pbstr)
put_CommandText(BSTR bstr)
get_CommandTimeout(LONG *pl)
put_CommandTimeout(LONG Timeout)
get_CommandType(CommandTypeEnum *plCmdType)
put_CommandType(CommandTypeEnum lCmdType)
get_Name(BSTR *pbstrName)
put_Name(BSTR bstrName)
get_Prepared(VARIANT_BOOL *pfPrepared)
put_Prepared(VARIANT_BOOL fPrepared)
get_State(LONG *plObjState)
get_Parameters(ADOParameters **ppvObject)
See Also
Command Object (ADO )
Error Object Properties, Methods, and Events
10/1/2018 • 2 minutes to read • Edit Online
Properties
Description Property
HelpContext, HelpFile Properties
NativeError Property
Number Property
Source Property (ADO Error)
SQLState Property
Methods
None.
Events
None.
See Also
Error Object
Command (Visual C++ Syntax Index with #import)
10/1/2018 • 2 minutes to read • Edit Online
Methods
HRESULT Cancel( );
_RecordsetPtr Execute( VARIANT * RecordsAffected, VARIANT * Parameters, long Options );
_ParameterPtr CreateParameter( _bstr_t Name, enum DataTypeEnum Type, enum ParameterDirectionEnum Direction,
long Size, const _variant_t & Value = vtMissing );
Properties
_ConnectionPtr GetActiveConnection( );
void PutRefActiveConnection( struct _Connection * ppvObject );
void PutActiveConnection( const _variant_t & ppvObject );
__declspec(property(get=GetActiveConnection,put=PutRefActiveConnection)) _ConnectionPtr ActiveConnection;
_bstr_t GetCommandText( );
void PutCommandText( _bstr_t pbstr );
__declspec(property(get=GetCommandText,put=PutCommandText)) _bstr_t
CommandText;
long GetCommandTimeout( );
void PutCommandTimeout( long pl );
__declspec(property(get=GetCommandTimeout,put=PutCommandTimeout)) long CommandTimeout;
void PutCommandType( enum CommandTypeEnum plCmdType );
enum CommandTypeEnum GetCommandType( );
__declspec(property(get=GetCommandType,put=PutCommandType)) enum CommandTypeEnum CommandType;
VARIANT_BOOL GetPrepared( );
void PutPrepared( VARIANT_BOOL pfPrepared );
__declspec(property(get=GetPrepared,put=PutPrepared)) VARIANT_BOOL Prepared;
ParametersPtr GetParameters( );
__declspec(property(get=GetParameters)) ParametersPtr Parameters;
_bstr_t GetName( );
void PutName( _bstr_t pbstrName );
__declspec(property(get=GetName,put=PutName)) _bstr_t Name;
long GetState( );
__declspec(property(get=GetState)) long State;
See Also
Command Object (ADO )
Update and CancelUpdate Methods Example (VC++)
10/1/2018 • 4 minutes to read • Edit Online
This example demonstrates the Update method in conjunction with the CancelUpdate method.
// Update_CancelUpdate_Methods_Sample.cpp
// compile with: /EHsc /c
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <stdio.h>
#include <ole2.h>
#include <malloc.h>
#include <conio.h>
#include "icrsint.h"
END_ADO_BINDING()
public:
CHAR m_sze_lname[31];
ULONG le_lnameStatus;
CHAR m_sze_fname[21];
ULONG le_fnameStatus;
};
END_ADO_BINDING()
public:
CHAR m_sze_empid[10];
ULONG le_empidStatus;
CHAR m_sze_lname[31];
ULONG le_lnameStatus;
CHAR m_sze_fname[21];
ULONG le_fnameStatus;
};
// Function Declartion.
// Function Declartion.
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void UpdateX();
void UpdateX2();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
UpdateX();
UpdateX2();
::CoUninitialize();
}
void UpdateX() {
// Define ADO object pointers. // Initialize pointers on define.
// These are in the ADODB:: namespace.
_RecordsetPtr pRstEmployees = NULL;
try {
// Open recordset with names from Employee table.
TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));
pRstEmployees->CursorType = adOpenKeyset;
pRstEmployees->LockType = adLockOptimistic;
pRstEmployees->Open("SELECT fname, lname FROM Employee "
"ORDER BY lname",strCnn,adOpenKeyset,adLockOptimistic, adCmdText);
if ( toupper(chKey) == 'Y' )
pRstEmployees->Update();
else
pRstEmployees->CancelUpdate();
if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
}
void UpdateX2() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
_RecordsetPtr pRstEmployees = NULL;
try {
// Open a connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open(strCnn, "", "", NULL);
if ( toupper(chKey) == 'Y') {
pRstEmployees->Update();
catch(_com_error &e) {
// Display errors, if any. Pass connection pointer accessed from the Connection.
PrintProviderError(pConnection);
PrintComError(e);
}
if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
CancelUpdate Method (ADO )
Update Method
WillChangeRecord and RecordChangeComplete
Events (ADO)
10/1/2018 • 2 minutes to read • Edit Online
The WillChangeRecord event is called before one or more records (rows) in the Recordset change. The
RecordChangeComplete event is called after one or more records change.
Syntax
WillChangeRecord adReason, cRecords, adStatus, pRecordset
RecordChangeCompleteadReason, cRecords, pError, adStatus, pRecordset
Parameters
adReason
An EventReasonEnum value that specifies the reason for this event. Its value can be adRsnAddNew,
adRsnDelete, adRsnUpdate, adRsnUndoUpdate, adRsnUndoAddNew, adRsnUndoDelete, or
adRsnFirstChange.
cRecords
A Long value that indicates the number of records changing (affected).
pError
An Error object. It describes the error that occurred if the value of adStatus is adStatusErrorsOccurred;
otherwise it is not set.
adStatus
An EventStatusEnum status value.
When WillChangeRecord is called, this parameter is set to adStatusOK if the operation that caused the event
was successful. It is set to adStatusCantDeny if this event cannot request cancellation of the pending operation.
When RecordChangeComplete is called, this parameter is set to adStatusOK if the operation that caused the
event was successful, or to adStatusErrorsOccurred if the operation failed.
Before WillChangeRecord returns, set this parameter to adStatusCancel to request cancellation of the
operation that caused this event or set this parameter to adStatusUnwantedEvent to prevent subsequent
notifications.
Before RecordChangeComplete returns, set this parameter to adStatusUnwantedEvent to prevent
subsequent notifications.
pRecordset
A Recordset object. The Recordset for which this event occurred.
Remarks
A WillChangeRecord or RecordChangeComplete event may occur for the first changed field in a row due to
the following Recordset operations: Update, Delete, CancelUpdate, AddNew, UpdateBatch, and CancelBatch. The
value of the Recordset CursorType determines which operations cause the events to occur.
During the WillChangeRecord event, the Recordset Filter property is set to adFilterAffectedRecords. You
cannot change this property while processing the event.
You must set the adStatus parameter to adStatusUnwantedEvent for each possible adReason value to
completely stop event notification for any event that includes an adReason parameter.
See Also
ADO Events Model Example (VC++)
ADO Event Handler Summary
Connection (ADO for Visual C++ Syntax)
10/1/2018 • 2 minutes to read • Edit Online
Methods
BeginTrans(long *TransactionLevel)
CommitTrans(void)
RollbackTrans(void)
Cancel(void)
Close(void)
Execute(BSTR CommandText, VARIANT *RecordsAffected, long Options, _ADORecordset **ppiRset)
Open(BSTR ConnectionString, BSTR UserID, BSTR Password, long Options)
OpenSchema(SchemaEnum Schema, VARIANT Restrictions, VARIANT SchemaID, _ADORecordset **pprset)
Properties
get_Attributes(long *plAttr)
put_Attributes(long lAttr)
get_CommandTimeout(LONG *plTimeout)
put_CommandTimeout(LONG lTimeout)
get_ConnectionString(BSTR *pbstr)
put_ConnectionString(BSTR bstr)
get_ConnectionTimeout(LONG *plTimeout)
put_ConnectionTimeout(LONG lTimeout)
get_CursorLocation(CursorLocationEnum *plCursorLoc)
put_CursorLocation(CursorLocationEnum lCursorLoc)
get_DefaultDatabase(BSTR *pbstr)
put_DefaultDatabase(BSTR bstr)
get_IsolationLevel(IsolationLevelEnum *Level)
put_IsolationLevel(IsolationLevelEnum Level)
get_Mode(ConnectModeEnum *plMode)
put_Mode(ConnectModeEnum lMode)
get_Provider(BSTR *pbstr)
put_Provider(BSTR Provider)
get_State(LONG *plObjState)
get_Version(BSTR *pbstr)
get_Errors(ADOErrors **ppvObject)
Events
BeginTransComplete(LONG TransactionLevel, ADOError *pError, EventStatusEnum *adStatus, _ADOConnection
*pConnection)
CommitTransComplete(ADOError *pError, EventStatusEnum *adStatus, _ADOConnection *pConnection)
ConnectComplete(ADOError *pError, EventStatusEnum *adStatus, _ADOConnection *pConnection)
Disconnect(EventStatusEnum *adStatus, _ADOConnection *pConnection)
ExecuteComplete(LONG RecordsAffected, ADOError *pError, EventStatusEnum *adStatus, _ADOCommand *pCommand,
_ADORecordset *pRecordset, _ADOConnection *pConnection)
InfoMessage(ADOError *pError, EventStatusEnum *adStatus, _ADOConnection *pConnection)
RollbackTransComplete(ADOError *pError, EventStatusEnum *adStatus, _ADOConnection *pConnection)
WillConnect(BSTR *ConnectionString, BSTR *UserID, BSTR *Password, long *Options, EventStatusEnum *adStatus,
_ADOConnection *pConnection)
WillExecute(BSTR *Source, CursorTypeEnum *CursorType, LockTypeEnum *LockType, long *Options, EventStatusEnum
*adStatus, _ADOCommand *pCommand, _ADORecordset *pRecordset, _ADOConnection *pConnection)
See Also
Connection Object (ADO )
Optimize Property Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Field object dynamic Optimize property. The zip field of the Authors table in the
Pubs database is not indexed. Setting the Optimize property to True on the zip field authorizes ADO to build an
index that improves the performance of the Find method.
Example
// Optimize_Property_Sample.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void OptimizeX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
OptimizeX();
::CoUninitialize();
}
void OptimizeX() {
_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");
try {
TESTHR(pRst.CreateInstance(__uuidof(Recordset)));
if ( (pConnection->Errors->Count) > 0 ) {
long nCount = pConnection->Errors->Count;
See Also
Field Object
Optimize Property-Dynamic (ADO )
put_OLEDBCommand Method
10/1/2018 • 2 minutes to read • Edit Online
Syntax
HRESULT put_OLEDBCommand(
IUnknown *pOLEDBCommand
);
Parameters
pOLEDBCommand
[in] Pointer to an OLE DB Command object.
Applies To
IADOCommandConstruction
CommandType Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
NOTE
Do not use the CommandTypeEnum values of adCmdFile or adCmdTableDirect with CommandType. These values
can only be used as options with the Open and Requery methods of a Recordset.
Remarks
Use the CommandType property to optimize evaluation of the CommandText property.
If the CommandType property value is set to the default value, adCmdUnknown, you may experience
diminished performance because ADO must make calls to the provider to determine if the CommandText
property is an SQL statement, a stored procedure, or a table name. If you know what type of command you are
using, setting the CommandType property instructs ADO to go directly to the relevant code. If the
CommandType property does not match the type of command in the CommandText property, an error occurs
when you call the Execute method.
Applies To
Command Object (ADO )
See Also
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(VB )
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(VC++)
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(JScript)
ADO Enumerated Constants
10/1/2018 • 4 minutes to read • Edit Online
To assist in debugging, the ADO enumerations list a value for each constant. However, this value is purely
advisory, and may change from one release of ADO to another. Your code should only depend on the name, not
the actual value, of each enumerated constant.
StreamOpenOptionsEnum Specifies options for opening a Stream object. The values can
be combined with an AND operator. Specifies whether the
whole stream or the next line should be read from a Stream
object.
StreamReadEnum Specifies whether the whole stream or the next line should be
read from a Stream object. Specifies the type of data stored
in a Stream object.
This example demonstrates different ways of using the ConnectionString property to open a Connection object. It
also uses the ConnectionTimeout property to set a connection timeout period, and the State property to check the
state of the connections. The GetState function is required for this procedure to run.
NOTE
If you are connecting to a data source provider that supports Windows authentication, you should specify
Trusted_Connection=yes or Integrated Security = SSPI instead of user ID and password information in the connection
string.
// ConnectionStringSampleCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
// Function declarations
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void ConnectionStringX();
_bstr_t GetState(int intState);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if (FAILED(::CoInitialize(NULL)))
return 0;
ConnectionStringX();
::CoUninitialize();
}
void ConnectionStringX() {
// Define Connection object pointers. Initialize pointers on define. These are in the ADODB:: namespace
_ConnectionPtr pConnection1 = NULL;
_ConnectionPtr pConnection2 = NULL;
_ConnectionPtr pConnection3 = NULL;
_ConnectionPtr pConnection4 = NULL;
try {
// Open a connection using OLE DB syntax.
TESTHR(pConnection1.CreateInstance(__uuidof(Connection)));
pConnection1->ConnectionString = "Provider='sqloledb';Data Source='(local)';"
"Initial Catalog='Pubs';Integrated Security='SSPI';";
pConnection1->ConnectionTimeout = 30;
pConnection1->Open("", "", "",adConnectUnspecified);
printf("cnn1 state: %s\n", (LPCTSTR)GetState(pConnection1->State));
// Open a connection using a DSN and individual arguments instead of a connection string.
// It is assumed that you have create DSN 'DataPubs' with a user name as
// 'MyUserId' and password as 'MyPassword'.
TESTHR(pConnection4.CreateInstance(__uuidof(Connection)));
pConnection4->Open("DataPubs", "MyUserId", "MyPassword", adConnectUnspecified);
printf("cnn4 state: %s\n", (LPCTSTR)GetState(pConnection4->State));
}
catch(_com_error &e) {
// Notify user of any errors. Pass a connection pointer accessed from the Connection.
PrintProviderError(pConnection1);
if (pConnection2)
PrintProviderError(pConnection2);
if (pConnection3)
PrintProviderError(pConnection3);
if (pConnection4)
PrintProviderError(pConnection4);
PrintComError(e);
}
if (pConnection2)
if (pConnection2->State == adStateOpen)
pConnection2->Close();
if (pConnection3)
if (pConnection3->State == adStateOpen)
pConnection3->Close();
if (pConnection4)
if (pConnection4->State == adStateOpen)
pConnection4->Close();
}
if ( (pConnection->Errors->Count) > 0) {
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
See Also
Connection Object (ADO )
ConnectionString Property (ADO )
ConnectionTimeout Property (ADO )
State Property (ADO )
ParameterDirectionEnum
10/1/2018 • 2 minutes to read • Edit Online
Specifies whether the Parameter represents an input parameter, an output parameter, both an input and an output
parameter, or the return value from a stored procedure.
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.ParameterDirection.INPUT
AdoEnums.ParameterDirection.INPUTOUTPUT
AdoEnums.ParameterDirection.OUTPUT
AdoEnums.ParameterDirection.RETURNVALUE
AdoEnums.ParameterDirection.UNKNOWN
Applies To
Syntax
object.AppendChunk Data
Parameters
object
A Field or Parameter object.
Data
A Variant that contains the data to append to the object.
Remarks
Use the AppendChunk method on a Field or Parameter object to fill it with long binary or character data. In
situations where system memory is limited, you can use the AppendChunk method to manipulate long values
in portions rather than in their entirety.
Field
If the adFldLong bit in the Attributes property of a Field object is set to true, you can use the AppendChunk
method for that field.
The first AppendChunk call on a Field object writes data to the field, overwriting any existing data. Subsequent
AppendChunk calls add to existing data. If you are appending data to one field and then you set or read the
value of another field in the current record, ADO assumes that you are finished appending data to the first field. If
you call the AppendChunk method on the first field again, ADO interprets the call as a new AppendChunk
operation and overwrites the existing data. Accessing fields in other Recordset objects that are not clones of the
first Recordset object will not disrupt AppendChunk operations.
If there is no current record when you call AppendChunk on a Field object, an error occurs.
NOTE
The AppendChunk method does not operate on Field objects of a Record Object (ADO) object. It does not perform any
operation and will produce a run-time error.
Parameter
If the adParamLong bit in the Attributes property of a Parameter object is set to true, you can use the
AppendChunk method for that parameter.
The first AppendChunk call on a Parameter object writes data to the parameter, overwriting any existing data.
Subsequent AppendChunk calls on a Parameter object add to existing parameter data. An AppendChunk call
that passes a null value discards all of the parameter data.
Applies To
See Also
AppendChunk and GetChunk Methods Example (VB )
AppendChunk and GetChunk Methods Example (VC++)
Attributes Property (ADO )
GetChunk Method (ADO )
CommandTimeout Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Indicates how long to wait while executing a command before terminating the attempt and generating an error.
Remarks
Use the CommandTimeout property on a Connection object or Command object to allow the cancellation of
an Execute method call, due to delays from network traffic or heavy server use. If the interval set in the
CommandTimeout property elapses before the command completes execution, an error occurs and ADO
cancels the command. If you set the property to zero, ADO will wait indefinitely until the execution is complete.
Make sure the provider and data source to which you are writing code support the CommandTimeout
functionality.
The CommandTimeout setting on a Connection object has no effect on the CommandTimeout setting on a
Command object on the same Connection; that is, the Command object's CommandTimeout property does
not inherit the value of the Connection object's CommandTimeout value.
On a Connection object, the CommandTimeout property remains read/write after the Connection is
opened.
Applies To
See Also
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(VB )
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(VC++)
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(JScript)
ConnectionTimeout Property (ADO )
OriginalValue and UnderlyingValue Properties
Example (VC++)
10/1/2018 • 3 minutes to read • Edit Online
This example demonstrates the OriginalValue and UnderlyingValue properties by displaying a message if a
record's underlying data has changed during a Recordset batch update.
Example
// BeginOriginalValueCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
#include "icrsint.h"
END_ADO_BINDING()
public:
CHAR m_szau_Title_id[7];
ULONG lau_Title_idStatus;
CHAR m_szau_Type[13];
ULONG lau_TypeStatus;
};
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void OriginalValueX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
OriginalValueX();
::CoUninitialize();
}
void OriginalValueX() {
// Define ADO object pointers, initialize pointers on define. These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
FieldPtr pFldType = NULL;
_RecordsetPtr pRstTitles = NULL;
try {
_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");
// Open connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open (strCnn, "", "", adConnectUnspecified);
if (pRstTitles)
if (pRstTitles->State == adStateOpen) {
// Cancel the update because this is a demonstration.
pRstTitles->CancelBatch(adAffectAll);
pRstTitles->Close();
}
if (pConnection)
if (pConnection->State == adStateOpen) {
// Restore Original Values.
pConnection->Execute(strSQLRestore, NULL, 0);
pConnection->Close();
}
};
if ( (pConnection->Errors->Count) > 0 ) {
long nCount = pConnection->Errors->Count;
See Also
OriginalValue Property (ADO )
Recordset Object (ADO )
UnderlyingValue Property
Prompt Property-Dynamic (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Specifies whether the OLE DB provider should prompt the user for initialization information.
Remarks
Prompt is a dynamic property, which may be appended to the Connection object's Properties collection by the
OLE DB provider. To prompt for initialization information, OLE DB providers will typically display a dialog box to
the user.
Dynamic properties of a Connection object are lost when the Connection is closed. The Prompt property must
be reset before re-opening the Connection to use a value other than the default.
NOTE
Do not specify that the provider should prompt the user in scenarios in which the user will not be able to respond to the
dialog box. For example, the user will not be able to respond if the application is running on a server system instead of on
the user's client, or if the application is running on a system with no user logged on. In these cases, the application will wait
indefinitely for a response and seem to lock up.
Usage
Set cn = New Connection
cn.Provider = "SQLOLEDB"
cn.Properties("Prompt") = adPromptNever ' do not prompt the user
Applies To
Connection Object (ADO )
Record (ADO for Visual C++ Syntax)
10/1/2018 • 2 minutes to read • Edit Online
Methods
Cancel(void)
Close(void)
CopyRecord(BSTR Source, BSTR Destination, BSTR UserName, BSTR Password, CopyRecordOptionsEnum Options,
VARIANT_BOOL Async, BSTR *pbstrNewURL)
DeleteRecord(BSTR Source, VARIANT_BOOL Async)
GetChildren(_ADORecordset **ppRSet)
MoveRecord(BSTR Source, BSTR Destination, BSTR UserName, BSTR Password, MoveRecordOptionsEnum Options,
VARIANT_BOOL Async, BSTR *pbstrNewURL)
Open(VARIANT Source, VARIANT ActiveConnection, ConnectModeEnum Mode, RecordCreateOptionsEnum CreateOptions,
RecordOpenOptionsEnum Options, BSTR UserName, BSTR Password)
Properties
get_ActiveConnection(VARIANT *pvar)
put_ActiveConnection(BSTR bstrConn)
putref_ActiveConnection(_ADOConnection *Con)
get_Fields(ADOFields **ppFlds)
get_Mode(ConnectModeEnum *pMode)
put_Mode(ConnectModeEnum Mode)
get_ParentURL(BSTR *pbstrParentURL)
get_RecordType(RecordTypeEnum *pType)
get_Source(VARIANT *pvar)
put_Source(BSTR Source)
putref_Source(IDispatch *Source)
get_State(ObjectStateEnum *pState)
See Also
Record Object (ADO )
AbsolutePosition and CursorLocation Properties
Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates how the AbsolutePosition property can track the progress of a loop that enumerates
all the records of a Recordset. It uses the CursorLocation property to enable the AbsolutePosition property by
setting the cursor to a client cursor.
'BeginAbsolutePositionVB
'Open connection
Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn
' clean up
rstEmployees.Close
Cnxn.Close
Set rstEmployees = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstEmployees Is Nothing Then
If rstEmployees.State = adStateOpen Then rstEmployees.Close
End If
Set rstEmployees = Nothing
See Also
AbsolutePosition Property (ADO )
CursorLocation Property (ADO )
Recordset Object (ADO )
DeleteRecord and MoveRecord Methods Example
(VB)
11/13/2018 • 2 minutes to read • Edit Online
This example demonstrates how to copy, move, edit, and delete the contents of a text file published to a Web folder.
Other properties and methods used include GetChildren, ParentURL, Source, and Flush.
'BeginDeleteRecordVB
'Note:
' IIS must be running for this sample to work. To
' use this sample you must:
'
' 1. create folders named "test" and "test2"
' in the root web folder of https://MyServer
'
' 2. Create a text file named "test2.txt" in the
' "test" folder.
' 3. Replace "MyServer" with the appropriate web
' server name.
' move the file from the subfolder back to original location
strDestFolder = "test2/"
rcDestFolder.Open strDestFolder, Cnxn ', adOpenIfExists 'Or adCreateCollection
Set rsDestFolder = rcDestFolder.GetChildren
rsDestFolder.MoveFirst
' clean up
rsDestFolder.Close
Cnxn.Close
Set rsDestFolder = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rsDestFolder Is Nothing Then
If rsDestFolder.State = adStateOpen Then rsDestFolder.Close
End If
Set rsDestFolder = Nothing
This example uses the AppendChunk and GetChunk methods to fill an image field with data from another record.
'BeginAppendChunkVB
' Open the pub_info table with a cursor that allows updates
Set rstPubInfo = New ADODB.Recordset
strSQLPubInfo = "pub_info"
rstPubInfo.Open strSQLPubInfo, Cnxn, adOpenKeyset, adLockOptimistic, adCmdTable
' clean up
rstPubInfo.Close
Cnxn.Close
Set rstPubInfo = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstPubInfo Is Nothing Then
If rstPubInfo.State = adStateOpen Then rstPubInfo.Close
End If
Set rstPubInfo = Nothing
See Also
AppendChunk Method (ADO )
Field Object
GetChunk Method (ADO )
Parameter Object
AbsolutePosition and CursorLocation Properties
Example (JScript)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates how the AbsolutePosition property can track the progress of a loop that enumerates all
the records of a Recordset. It uses the CursorLocation property to enable the AbsolutePosition property by
setting the cursor to a client cursor. Cut and paste the following code to Notepad or another text editor, and save it
as AbsolutePositionJS.asp.
<html>
<head>
<title>AbsolutePosition and CursorLocation Properties Example (JScript)</title>
<style>
<!--
BODY {
font-family: 'Verdana','Arial','Helvetica',sans-serif;
BACKGROUND-COLOR:white;
COLOR:black;
}
.thead2 {
background-color: #800000;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
color: white;
}
.tbody {
text-align: center;
background-color: #f7efde;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
}
-->
</style>
</head>
<body>
<h1>AbsolutePosition and CursorLocation Properties Example (JScript)</h1>
<%
// connection and recordset variables
var strCnxn = "Provider='sqloledb';Data Source=" + Request.ServerVariables("SERVER_NAME") + ";" +
"Initial Catalog='Northwind';Integrated Security='SSPI';";
var rsEmployee = Server.CreateObject("ADODB.Recordset");
// display string
var strMessage;
try
{
// Open a recordset on the Employee table using
// a client-side cursor to enable AbsolutePosition property.
rsEmployee.CursorLocation = adUseClient;
rsEmployee.Open("employees", strCnxn, adOpenStatic, adLockOptimistic, adCmdTable);
while (!rsEmployee.EOF)
{
strMessage = "";
</html>
<!-- EndAbsolutePositionJS -->
See Also
AbsolutePosition Property (ADO )
CursorLocation Property (ADO )
Recordset Object (ADO )
ActualSize and DefinedSize Properties Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the ActualSize and DefinedSize properties to display the defined size and actual size of a field.
'BeginActualSizeVB
SQLStores = "Suppliers"
rstStores.Open SQLStores, strCnxn, adOpenForwardOnly, adLockReadOnly, adCmdTable
'the above two lines of code are identical as the default values for
'CursorType and LockType arguments match those indicated
Do Until rstStores.EOF
strMessage = "Company name: " & rstStores!CompanyName & _
vbCrLf & "Defined size: " & _
rstStores!CompanyName.DefinedSize & _
vbCrLf & "Actual size: " & _
rstStores!CompanyName.ActualSize & vbCrLf
' clean up
rstStores.Close
Set rstStores = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstStores Is Nothing Then
If rstStores.State = adStateOpen Then rstStores.Close
End If
Set rstStores = Nothing
See Also
ActualSize Property (ADO )
DefinedSize Property
Field Object
ConnectOptionEnum
10/1/2018 • 2 minutes to read • Edit Online
Specifies whether the Open method of a Connection object should return after the connection is established
(synchronously) or before (asynchronously).
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.ConnectOption.ASYNCCONNECT
AdoEnums.ConnectOption.CONNECTUNSPECIFIED
Applies To
Open Method (ADO Connection)
ADO API Reference
10/1/2018 • 2 minutes to read • Edit Online
This section of the ADO documentation contains topics for each ADO object, collection, property, dynamic
property, method, event, and enumeration. In addition, it contains a list of ADO syntax indexes to be used with
Microsoft Visual C++ and Windows Foundation Classes (WFC ).
For more information, search for a specific topic in the index or refer to the following topics:
ADO Object Model
ADO Objects and Interfaces
ADO Collections
ADO Properties
ADO Dynamic Properties
ADO Methods
ADO Events
ADO Enumerated Constants
ADO Syntax Indexes
ADO Code Examples
See Also
Appendix D: ADO Samples
Microsoft ActiveX Data Objects (ADO )
Appendix C: Programming with ADO
Appendix A: Providers
ADO History
ReadText Method
11/13/2018 • 2 minutes to read • Edit Online
Syntax
String = Stream.ReadText ( NumChars)
Parameters
NumChars
Optional. A Long value that specifies the number of characters to read from the file, or a StreamReadEnum value.
The default value is adReadAll.
Return Value
The ReadText method reads a specified number of characters, an entire line, or the entire stream from a Stream
object and returns the resulting string.
Remarks
If NumChar is more than the number of characters left in the stream, only the characters remaining are returned.
The string read is not padded to match the length specified by NumChar. If there are no characters left to read, a
variant whose value is null is returned. ReadText cannot be used to read backwards.
NOTE
The ReadText method is used with text streams (Type is adTypeText). For binary streams ( Type is adTypeBinary), use
Read.
Queries that result in a large amount of XML data being returned through the ReadText method of the ActiveX
Data Object (ADO ) Stream object may take a great deal of time to execute; if this is done in a COM+ component
that is invoked from an ASP page, the user's session may time out. ADO converts Stream object data from UTF -8
encoding to Unicode; the frequent memory reallocation involved in conversion of such a large quantity of data at
once is quite time-consuming. To resolve, make repeated calls to the ReadText method of the ADO command
object, and specify a smaller number of characters. Tests have shown that a value equivalent to 128K (131,072) is
optimal. Response time decreases as this value is decreased. For more information, see Knowledge Base article
280067, "PRB: Retrieving very large XML Documents from SQL Server 2000 by using ReadText method of ADO
stream object may be slow", in the Microsoft Knowledge Base at https://support.microsoft.com.
Applies To
Stream Object (ADO )
See Also
Read Method
FieldEnum
10/1/2018 • 2 minutes to read • Edit Online
Remarks
These constants provide a "shortcut" to accessing special fields associated with a Record. Retrieve the Field object
from the Fields collection, and then obtain its contents with the Field object's Value property.
This example demonstrates the ActiveCommand property. Cut and paste the following code to Notepad or
another text editor, and save it as ActiveCommandJS.asp.
<%
// user input
strName = new String(Request.Form("ContactName"))
%>
<html>
<head>
<title>ActiveCommand Property Example (JScript)</title>
<style>
<!--
BODY {
font-family: 'Verdana','Arial','Helvetica',sans-serif;
BACKGROUND-COLOR:white;
COLOR:black;
}
-->
</style>
</head>
<body bgcolor="White">
<%
if (strName.length > 0)
{
// connection and recordset variables
var Cnxn = Server.CreateObject("ADODB.Connection")
var strCnxn = "Provider='sqloledb';Data Source=" + Request.ServerVariables("SERVER_NAME") + ";" +
"Initial Catalog='Northwind';Integrated Security='SSPI';";
var cmdContact = Server.CreateObject("ADODB.Command");
var rsContact = Server.CreateObject("ADODB.Recordset");
// display variables
var strMessage;
try
{
// open connection
Cnxn.Open(strCnxn);
rsContact = cmdContact.Execute();
while(!rsContact.EOF){
while(!rsContact.EOF){
// start new line
strMessage = "<P>";
// get data
strMessage += rsContact("ContactName")
// show data
Response.Write(strMessage);
<hr>
</html>
<!-- EndActiveCommandJS -->
See Also
ActiveCommand Property (ADO )
Command Object (ADO )
Recordset Object (ADO )
StreamWriteEnum
10/1/2018 • 2 minutes to read • Edit Online
Specifies whether a line separator is appended to the string written to a Stream object.
ADO/WFC Equivalent
These constants do not have ADO/WFC equivalents.
Applies To
WriteText Method
BOF, EOF, and Bookmark Properties Example (VC++)
10/1/2018 • 3 minutes to read • Edit Online
The first function in this example uses the BOF and EOF properties to display a message if a user tries to move
past the first or last record of a Recordset. It uses the Bookmark property to let the user flag a record in a
Recordset and return to it later.
The second function uses the Bookmark property to place the Bookmark of every other record from a Recordset
into an array, and then filters the Recordset using the array.
Example
// BOF_EOF_Bookmark.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include "conio.h"
#include "icrsint.h"
END_ADO_BINDING()
public:
CHAR m_szau_id[20];
ULONG lau_idStatus;
CHAR m_szau_fname[40];
ULONG lau_fnameStatus;
CHAR m_szau_lname[40];
ULONG lau_lnameStatus;
};
// Function declaration
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void AppendX();
void PrintProviderError(_ConnectionPtr pConnection);
int main() {
HRESULT hr = S_OK;
if (FAILED(::CoInitialize(NULL)))
return -1;
AppendX();
::CoUninitialize();
}
void AppendX() {
HRESULT hr = S_OK;
// Define ADO object pointers. Initialize pointers on define. These are in the ADODB:: namespace.
_RecordsetPtr pRstByRoyalty = NULL;
_RecordsetPtr pRstAuthors = NULL;
_CommandPtr pcmdByRoyalty = NULL;
_ParameterPtr pprmByRoyalty = NULL;
_ConnectionPtr pConnection = NULL;
int intRoyalty;
VARIANT vtRoyalty;
try {
// Open a Connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
hr = pConnection->Open(strCnn, "", "", adConnectUnspecified);
pConnection->CursorLocation = adUseClient;
// Define Integer/variant.
vtRoyalty.vt = VT_I2;
vtRoyalty.iVal = intRoyalty;
pprmByRoyalty = pcmdByRoyalty->CreateParameter("percentage", adInteger, adParamInput, sizeof(int),
vtRoyalty);
pcmdByRoyalty->Parameters->Append(pprmByRoyalty);
pprmByRoyalty->Value = vtRoyalty;
// You have to explicitly pass the default Cursor type and LockType to the Recordset here
hr = pRstAuthors->Open("authors", _variant_t((IDispatch*)pConnection, true), adOpenForwardOnly,
adLockReadOnly, adCmdTable);
// Open an IADORecordBinding interface pointer which we'll use for Binding Recordset to a class
TESTHR(pRstAuthors->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));
// Print current data in the recordset, adding author names from author table.
printf("Authors with %d percent royalty ", intRoyalty);
while(!(pRstByRoyalty->EndOfFile)) {
strAuthorID = pRstByRoyalty->Fields->Item["au_id"]->Value;
pRstAuthors->Filter = "au_id = '"+strAuthorID+"'";
pRstByRoyalty->MoveNext();
}
}
catch(_com_error &e) {
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
PrintProviderError(pConnection);
printf("\n Source : %s \n Description : %s \n", (LPCSTR)bstrSource, (LPCSTR)bstrDescription);
}
if (pRstByRoyalty)
if (pRstByRoyalty->State == adStateOpen)
pRstByRoyalty->Close();
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}
if ( (pConnection->Errors->Count) > 0) {
nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for (i = 0 ; i < nCount ; i++) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\n Error Description: %s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
Input
25
Sample Output
Authors with 25 percent royalty
724-80-9391, Stearns MacFeather
899-46-2035, Anne Ringer
See Also
BOF, EOF Properties (ADO )
Bookmark Property (ADO )
Recordset Object (ADO )
Recordset (ADO - WFC Syntax)
10/1/2018 • 2 minutes to read • Edit Online
package com.ms.wfc.data
Constructors
public Recordset()
public Recordset(Object r)
Methods
Events
For more information about ADO/WFC events, see ADO Event Instantiation by Language.
public void addOnEndOfRecordset(RecordsetEventHandler handler)
public void removeOnEndOfRecordset(RecordsetEventHandler handler)
public void addOnFetchComplete(RecordsetEventHandler handler)
public void removeOnFetchComplete(RecordsetEventHandler handler)
public void addOnFetchProgress(RecordsetEventHandler handler)
public void removeOnFetchProgress(RecordsetEventHandler handler)
public void addOnFieldChangeComplete(RecordsetEventHandler handler)
public void removeOnFieldChangeComplete(RecordsetEventHandler handler)
public void addOnMoveComplete(RecordsetEventHandler handler)
public void removeOnMoveComplete(RecordsetEventHandler handler)
public void addOnRecordChangeComplete(RecordsetEventHandler handler)
public void removeOnRecordChangeComplete(RecordsetEventHandler handler)
public void addOnRecordsetChangeComplete(RecordsetEventHandler handler)
public void removeOnRecordsetChangeComplete(RecordsetEventHandler handler)
public void addOnWillChangeField(RecordsetEventHandler handler)
public void removeOnWillChangeField(RecordsetEventHandler handler)
public void addOnWillChangeRecord(RecordsetEventHandler handler)
public void removeOnWillChangeRecord(RecordsetEventHandler handler)
public void addOnWillChangeRecordset(RecordsetEventHandler handler)
public void removeOnWillChangeRecordset(RecordsetEventHandler handler)
public void addOnWillMove(RecordsetEventHandler handler)
public void removeOnWillMove(RecordsetEventHandler handler)
See Also
Recordset Object (ADO )
UpdateBatch and CancelBatch Methods Example
(VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the UpdateBatch method in conjunction with the CancelBatch method.
// BeginUpdateBatchCpp.cpp
// compile with: /EHsc /c
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
#include "icrsint.h"
public:
CHAR m_szt_Title[81];
ULONG lt_TitleStatus;
CHAR m_szt_Type[13];
ULONG lt_TypeStatus;
};
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void UpdateBatchX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
UpdateBatchX();
::CoUninitialize();
}
void UpdateBatchX() {
HRESULT hr = S_OK;
try {
// Open titles table.
TESTHR(pRstTitles.CreateInstance(__uuidof(Recordset)));
pRstTitles->CursorType = adOpenKeyset;
pRstTitles->LockType = adLockBatchOptimistic;
pRstTitles->Open ("titles", strCnn, adOpenKeyset, adLockBatchOptimistic, adCmdTable);
system("cls");
while (!pRstTitles->EndOfFile) {
printf("%s - %s\n",
titlers.lt_TitleStatus == adFldOK ?
titlers.m_szt_Title :"<NULL>",
titlers.lt_TypeStatus == adFldOK ?
titlers.m_szt_Type :"<NULL>");
pRstTitles->MoveNext();
}
pRstTitles->MoveFirst();
if (pRstTitles)
if (pRstTitles->State == adStateOpen) {
pRstTitles->UpdateBatch(adAffectAll);
pRstTitles->Close();
}
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for (long i = 0 ; i < nCount ; i++) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
CancelBatch Method (ADO )
UpdateBatch Method
ADCPROP_UPDATERESYNC_ENUM
10/1/2018 • 2 minutes to read • Edit Online
Specifies whether the UpdateBatch method is followed by an implicit Resync method operation and if so, the
scope of that operation.
Applies To
Update Resync Property-Dynamic (ADO )
CompareEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.Compare.EQUAL
AdoEnums.Compare.GREATERTHAN
AdoEnums.Compare.LESSTHAN
AdoEnums.Compare.NOTCOMPARABLE
AdoEnums.Compare.NOTEQUAL
Applies To
CompareBookmarks Method (ADO )
See Also
CompareBookmarks Method (ADO )
Find Method Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Recordset object's Find method to locate and count the number of business titles in the
Pubs database. The example assumes the underlying provider does not support similar functionality.
'BeginFindVB
count = 0
rstTitles.Find "title_id LIKE 'BU%'"
' clean up
rstTitles.Close
Cnxn.Close
Set rstTitles = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
ErrorHandler:
' clean up
If Not rstTitles Is Nothing Then
If rstTitles.State = adStateOpen Then rstTitles.Close
End If
Set rstTitles = Nothing
See Also
Find Method (ADO )
Recordset Object (ADO )
Record (Visual C++ Syntax Index with #import)
10/1/2018 • 2 minutes to read • Edit Online
Methods
HRESULT Cancel( );
HRESULT Close( );
_RecordsetPtr GetChildren( );
Properties
_variant_t GetActiveConnection( );
void PutActiveConnection( _bstr_t pvar );
void PutRefActiveConnection( struct _Connection * pvar );
FieldsPtr GetFields( );
__declspec(property(get=GetFields)) FieldsPtr Fields;
_bstr_t GetParentURL( );
__declspec(property(get=GetParentURL)) _bstr_t ParentURL;
_variant_t GetSource( );
void PutSource( _bstr_t pvar );
void PutRefSource( IDispatch * pvar );
See Also
Record Object (ADO )
CopyRecord Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Record.CopyRecord (Source, Destination, UserName, Password, Options, Async)
Parameters
Source
Optional. A String value that contains a URL specifying the entity to be copied (for example, a file or directory). If
Source is omitted or specifies an empty string, the file or directory represented by the current Record will be
copied.
Destination
Optional. A String value that contains a URL specifying the location where Source will be copied.
UserName
Optional. A String value that contains the user ID that, if needed, authorizes access to Destination.
Password
Optional. A String value that contains the password that, if needed, verifies UserName.
Options
Optional. A CopyRecordOptionsEnum value that has a default value of adCopyUnspecified. Specifies the
behavior of this method.
Async
Optional. A Boolean value that, when True, specifies that this operation should be asynchronous.
Return Value
A String value that typically returns the value of Destination. However, the exact value returned is provider-
dependent.
Remarks
The values of Source and Destination must not be identical; otherwise, a run-time error occurs. At least one of the
server, path, or resource names must differ.
All children (for example, subdirectories) of Source are copied recursively, unless adCopyNonRecursive is
specified. In a recursive operation, Destination must not be a subdirectory of Source; otherwise, the operation will
not complete.
This method fails if Destination identifies an existing entity (for example, a file or directory), unless
adCopyOverWrite is specified.
IMPORTANT
Use the adCopyOverWrite option judiciously. For example, specifying this option when copying a file to a directory will
delete the directory and replace it with the file.
NOTE
URLs using the http scheme will automatically invoke the Microsoft OLE DB Provider for Internet Publishing. For more
information, see Absolute and Relative URLs.
Applies To
Record Object (ADO )
NativeError Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Return Value
Returns a Long value that indicates the error code.
Remarks
Use the NativeError property to retrieve the database-specific error information for a particular Error object. For
example, when using the Microsoft ODBC Provider for OLE DB with a Microsoft SQL Server database, native
error codes that originate from SQL Server pass through ODBC and the ODBC Provider to the ADO
NativeError property.
Applies To
Error Object
See Also
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VB )
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VC++)
Filter and RecordCount Properties Example (VC++)
10/1/2018 • 4 minutes to read • Edit Online
This example uses the Filter property to open a new Recordset based on a specified condition applied to an
existing Recordset. It uses the RecordCount property to show the number of records in the two Recordsets. The
FilterField function is required for this procedure to run.
Example
// BeginFilterCpp.cpp
// compile with: /EHsc /c
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <stdio.h>
#include <ole2.h>
#include <conio.h>
#include "icrsint.h"
END_ADO_BINDING()
public:
CHAR m_szP_pubname[50];
ULONG lP_pubnameStatus;
CHAR m_szP_country[50];
ULONG lP_countryStatus;
};
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void FilterX();
_RecordsetPtr FilterField(_RecordsetPtr rstTemp, _bstr_t strField, _bstr_t strFilter);
void FilterX2();
void PrintProviderError(_ConnectionPtr pCnn1);
void PrintComError(_com_error &e);
if (pstrRet == NULL)
return NULL;
if (!strrchr(strDest, '\n'))
// Exhaust the input buffer.
do {
fgets(strExBuff, sizeof(strExBuff), stdin);
} while (!strrchr(strExBuff, '\n'));
else
// Replace '\n' with '\0'
// Replace '\n' with '\0'
strDest[strrchr(strDest, '\n') - strDest] = '\0';
return pstrRet;
}
int main() {
HRESULT hr = S_OK;
if ( FAILED(::CoInitialize(NULL)) )
return -1;
FilterX();
FilterX2();
::CoUninitialize();
}
void FilterX() {
// Define ADO object pointers, initialize pointers on define. These are in the ADODB:: namespace.
_RecordsetPtr rstPublishers = NULL;
_RecordsetPtr rstPublishersCountry = NULL;
try {
// Open recordset with data from Publishers table.
rstPublishers.CreateInstance(__uuidof(Recordset));
rstPublishersCountry.CreateInstance(__uuidof(Recordset));
rstPublishers->CursorType = adOpenStatic;
if (boolFlag) {
if (strcmp(sz_CountryName,"")) {
// Open a filtered Recordset object.
rstPublishersCountry = FilterField(rstPublishers, "Country", strCountry);
recCount = rstPublishersCountry->GetRecordCount();
if (recCount == 0)
printf("\nNo publishers from that country.\n");
else {
// Print number of records for the original recordset object and the
// filtered Recordset object.
printf("\nOrders in original recordset:\n%d", intPublisherCount);
printf("\nOrders in filtered recordset (Country = '%s'): \n%d\n\n",
printf("\nOrders in filtered recordset (Country = '%s'): \n%d\n\n",
(LPCSTR)strCountry, rstPublishersCountry->RecordCount);
}
}
}
}
catch(_com_error &e) {
// Notify the user of errors if any.
_variant_t vtConnect = rstPublishers->GetActiveConnection();
void FilterX2() {
_RecordsetPtr rstPublishers;
CPublishers publishers;
while (!rstPublishers->EndOfFile) {
printf("%s, %s\n",
printf("%s, %s\n",
publishers.lP_pubnameStatus == adFldOK ?
publishers.m_szP_pubname: "<NULL>",
publishers.lP_countryStatus == adFldOK ?
publishers.m_szP_country: "<NULL>");
rstPublishers->MoveNext();
}
}
catch (_com_error &e) {
// Notify the user of errors if any.
_variant_t vtConnect = rstPublishers->GetActiveConnection();
if (rstPublishers)
if (rstPublishers->State == adStateOpen)
rstPublishers->Close();
}
if ( (pCnn1->Errors->Count) > 0) {
long nCount = pCnn1->Errors->Count;
// Collection ranges from 0 to nCount -1.
for (long i = 0 ; i < nCount ; i++) {
pErr = pCnn1->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
Sample Input
USA
Sample Output
Orders in original recordset:
8
Orders in filtered recordset (Country = 'USA'):
6
See Also
Filter Property
RecordCount Property (ADO )
Recordset Object (ADO )
RecordsetEvents (Visual C++ Syntax Index with
#import)
10/1/2018 • 2 minutes to read • Edit Online
Events
HRESULT WillChangeField( long cFields, const
_variant_t & Fields, enum EventStatusEnum * adStatus, struct
_Recordset * pRecordset );
This example demonstrates how the StayInSync property facilitates accessing rows in a hierarchical Recordset.
The outer loop displays each author's first and last name, state, and identification. The appended Recordset for
each row is retrieved from the Fields collection and automatically assigned to rstTitleAuthor by the StayInSync
property whenever the parent Recordset moves to a new row. The inner loop displays four fields from each row in
the appended recordset.
'BeginStayInSyncVB
Public Sub Main()
On Error GoTo ErrorHandler
Do Until rstTitleAuthor.EOF
Debug.Print rstTitleAuthor(0) & " " & rstTitleAuthor(1) & " " & _
rstTitleAuthor(2) & " " & rstTitleAuthor(3)
rstTitleAuthor.MoveNext
Loop
rst.MoveNext
Loop
' Clean up
rst.Close
Cnxn.Close
Set rst = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' Clean up
If Not rst Is Nothing Then
If rst.State = adStateOpen Then rst.Close
End If
Set rst = Nothing
See Also
Fields Collection (ADO )
Recordset Object (ADO )
StayInSync Property
BOF, EOF, and Bookmark Properties Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the BOF and EOF properties to display a message if a user tries to move past the first or last
record of a Recordset. It uses the Bookmark property to let the user flag a record in a Recordset and return to it
later.
'BeginBOFVB
rstPublishers.MoveFirst
Do Until rstPublishers.EOF
' Display information about current record
' and get user input
strMessage = "Publisher: " & rstPublishers!pub_name & _
vbCr & "(record " & rstPublishers.AbsolutePosition & _
" of " & rstPublishers.RecordCount & ")" & vbCr & vbCr & _
"Enter command:" & vbCr & _
"[1 - next / 2 - previous /" & vbCr & _
"3 - set bookmark / 4 - go to bookmark]"
intCommand = Val(InputBox(strMessage))
' clean up
rstPublishers.Close
Cnxn.Close
Set rstPublishers = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstPublishers Is Nothing Then
If rstPublishers.State = adStateOpen Then rstPublishers.Close
End If
Set rstPublishers = Nothing
This example uses the Bookmark and Filter properties to create a limited view of the Recordset. Only records
referenced by the array of bookmarks are accessible.
See Also
BOF, EOF Properties (ADO )
Bookmark Property (ADO )
Recordset Object (ADO )
CursorType Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the CursorType property to specify the type of cursor that should be used when opening the Recordset
object.
Only a setting of adOpenStatic is supported if the CursorLocation property is set to adUseClient. If an
unsupported value is set, then no error will result; the closest supported CursorType will be used instead.
If a provider does not support the requested cursor type, it may return another cursor type. The CursorType
property will change to match the actual cursor type in use when the Recordset object is open. To verify specific
functionality of the returned cursor, use the Supports method. After you close the Recordset, the CursorType
property reverts to its original setting.
The following chart shows the provider functionality (identified by Supports method constants) required for
each cursor type.
adOpenForwardOnly none
adOpenDynamic adMovePrevious
NOTE
Although Supports(adUpdateBatch) may be true for dynamic and forward-only cursors, for batch updates you should
use either a keyset or static cursor. Set the LockType property to adLockBatchOptimistic and the CursorLocation
property to adUseClient to enable the Cursor Service for OLE DB, which is required for batch updates.
The CursorType property is read/write when the Recordset is closed and read-only when it is open.
NOTE
Remote Data Service Usage When used on a client-side Recordset object, the CursorType property can be set only to
adOpenStatic.
Applies To
Recordset Object (ADO )
See Also
CursorType, LockType, and EditMode Properties Example (VB )
CursorType, LockType, and EditMode Properties Example (VC++)
Supports Method
PageCount Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Return Value
Returns a Long value that indicates the number of pages in the Recordset.
Remarks
Use the PageCount property to determine how many pages of data are in the Recordset object. Pages are
groups of records whose size equals the PageSize property setting. Even if the last page is incomplete because
there are fewer records than the PageSize value, it counts as an additional page in the PageCount value. If the
Recordset object does not support this property, the value will be -1 to indicate that the PageCount is
indeterminable.
See the PageSize and AbsolutePage properties for more on page functionality.
Applies To
Recordset Object (ADO )
See Also
AbsolutePage, PageCount, and PageSize Properties Example (VB )
AbsolutePage, PageCount, and PageSize Properties Example (VC++)
AbsolutePage Property (ADO )
PageSize Property (ADO )
RecordCount Property (ADO )
ADO Collections
10/1/2018 • 2 minutes to read • Edit Online
The relationships between these collections and the ADO objects are represented in the ADO Object Model.
Each collection can contain its corresponding object. For example, an Error object can be contained in an Errors
collection. For more information about objects, see ADO Objects or a specific object topic.
See Also
ADO API Reference
ADO Dynamic Properties
ADO Enumerated Constants
Appendix B: ADO Errors
ADO Events
ADO Methods
ADO Object Model
ADO Objects and Interfaces
ADO Properties
Append and CreateParameter Methods Example
(VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Append and CreateParameter methods to execute a stored procedure with an input
parameter.
Example
// BeginAppendCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include "conio.h"
#include "icrsint.h"
END_ADO_BINDING()
public:
CHAR m_szau_id[20];
ULONG lau_idStatus;
CHAR m_szau_fname[40];
ULONG lau_fnameStatus;
CHAR m_szau_lname[40];
ULONG lau_lnameStatus;
};
// Function declaration
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void AppendX();
void PrintProviderError(_ConnectionPtr pConnection);
int main() {
HRESULT hr = S_OK;
if (FAILED(::CoInitialize(NULL)))
return -1;
AppendX();
::CoUninitialize();
}
void AppendX() {
HRESULT hr = S_OK;
// Define ADO object pointers. Initialize pointers on define. These are in the ADODB:: namespace.
_RecordsetPtr pRstByRoyalty = NULL;
_RecordsetPtr pRstByRoyalty = NULL;
_RecordsetPtr pRstAuthors = NULL;
_CommandPtr pcmdByRoyalty = NULL;
_ParameterPtr pprmByRoyalty = NULL;
_ConnectionPtr pConnection = NULL;
int intRoyalty;
VARIANT vtRoyalty;
try {
// Open a Connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
hr = pConnection->Open(strCnn, "", "", adConnectUnspecified);
pConnection->CursorLocation = adUseClient;
// Define Integer/variant.
vtRoyalty.vt = VT_I2;
vtRoyalty.iVal = intRoyalty;
pprmByRoyalty = pcmdByRoyalty->CreateParameter("percentage", adInteger, adParamInput, sizeof(int),
vtRoyalty);
pcmdByRoyalty->Parameters->Append(pprmByRoyalty);
pprmByRoyalty->Value = vtRoyalty;
// You have to explicitly pass the default Cursor type and LockType to the Recordset here
hr = pRstAuthors->Open("authors", _variant_t((IDispatch*)pConnection, true), adOpenForwardOnly,
adLockReadOnly, adCmdTable);
// Open an IADORecordBinding interface pointer which we'll use for Binding Recordset to a class
TESTHR(pRstAuthors->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));
//Print current data in the recordset, adding author names from author table.
printf("Authors with %d percent royalty ", intRoyalty);
while(!(pRstByRoyalty->EndOfFile)) {
strAuthorID = pRstByRoyalty->Fields->Item["au_id"]->Value;
pRstAuthors->Filter = "au_id = '"+strAuthorID+"'";
if (pRstByRoyalty)
if (pRstByRoyalty->State == adStateOpen)
pRstByRoyalty->Close();
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}
if ( (pConnection->Errors->Count) > 0) {
nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for (i = 0 ; i < nCount ; i++) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\n Error Description: %s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
Input
25
Sample Output
Authors with 25 percent royalty
724-80-9391, Stearns MacFeather
899-46-2035, Anne Ringer
See Also
Append Method (ADO )
CreateParameter Method (ADO )
CopyTo Method (ADO)
11/28/2018 • 2 minutes to read • Edit Online
Copies the specified number of characters or bytes (depending on Type) in the Stream to another Stream object.
Syntax
Stream.CopyTo DestStream, NumChars
Parameters
DestStream
An object variable value that contains a reference to an open Stream object. The current Stream is copied to the
destination Stream specified by DestStream. The destination Stream must already be open. If not, a run-time
error occurs.
NOTE
The DestStream parameter may not be a proxy of Stream object because this requires access to a private interface on the
Stream object that cannot be remoted to the client.
NumChars
Optional. An Integer value that specifies the number of bytes or characters to be copied from the current position
in the source Stream to the destination Stream. The default value is -1, which specifies that all characters or bytes
are copied from the current position to EOS.
Remarks
This method copies the specified number of characters or bytes, starting from the current position specified by the
Position property. If the specified number is more than the available number of bytes until EOS, then only
characters or bytes from the current position to EOS are copied. If the value of NumChars is -1, or omitted, all
characters or bytes starting from the current position are copied.
If there are existing characters or bytes in the destination stream, all contents beyond the point where the copy
ends remain, and are not truncated. Position becomes the byte immediately following the last byte copied. If you
want to truncate these bytes, call SetEOS.
CopyTo should be used to copy data to a destination Stream of the same type as the source Stream (their Type
property settings are both adTypeText or both adTypeBinary). For text Stream objects, you can change the
Charset property setting of the destination Stream to translate from one character set to another. Also, text
Stream objects can be successfully copied into binary Stream objects, but binary Stream objects cannot be
copied into text Stream objects.
Applies To
Stream Object (ADO )
Item Property Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates how the Item property accesses members of a collection. The example opens the
Authors table of the Pubs database with a parameterized command.
The parameter in the command issued against the database is accessed from the Command object's Parameters
collection by index and name. The fields of the returned Recordset are then accessed from that object's Fields
collection by index and name.
'BeginItemVB
Dim ix As Integer
Dim limit As Long
Dim Column(0 To 8) As Variant
'Set the array with the Authors table field (column) names
Column(0) = "au_id"
Column(1) = "au_lname"
Column(2) = "au_fname"
Column(3) = "phone"
Column(4) = "address"
Column(5) = "city"
Column(6) = "state"
Column(7) = "zip"
Column(8) = "contract"
rstAuthors.MoveFirst
limit = rstAuthors.Fields.Count - 1
For ix = 0 To limit
Set fld = rstAuthors.Fields.Item(ix)
Debug.Print "Field "; ix; ": Name = '"; fld.Name; _
"', Value = '"; fld.Value; "'"
Next ix
Debug.Print
rstAuthors.MoveFirst
For ix = 0 To 8
Set fld = rstAuthors.Fields.Item(Column(ix))
Debug.Print "Field name = '"; fld.Name; "', Value = '"; fld.Value; "'"
Next ix
' clean up
rstAuthors.Close
Cnxn.Close
Set rstAuthors = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstAuthors Is Nothing Then
If rstAuthors.State = adStateOpen Then rstAuthors.Close
End If
Set rstAuthors = Nothing
End Sub
'EndItemVB
See Also
Command Object (ADO )
Fields Collection (ADO )
Item Property (ADO )
Parameters Collection (ADO )
Recordset Object (ADO )
GetChildren Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Set recordset = record.GetChildren
Return Value
A Recordset object for which each row represents a child of the current Record object. For example, the children
of a Record that represents a directory would be the files and subdirectories contained within the parent
directory.
Remarks
The provider determines what columns exist in the returned Recordset. For example, a document source provider
always returns a resource Recordset.
Applies To
This example demonstrates setting the CursorType and LockType properties before opening a Recordset. It also
shows the value of the EditMode property under various conditions. The EditModeOutput function is required for
this procedure to run.
Example
// CursorType_LockType_EditMode_Property_Example.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
// Function declaration
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void EditModeX();
void EditModeOutput(char *, int);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
EditModeX();
::CoUninitialize();
}
void EditModeX() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace.
_RecordsetPtr pRstEmployees = NULL;
_ConnectionPtr pConnection = NULL;
HRESULT hr = S_OK;
try {
// Open a connection
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
hr = pConnection->Open(strCnn, "", "", adConnectUnspecified);
pRstEmployees->CursorLocation = adUseClient;
pRstEmployees->CursorType = adOpenStatic;
pRstEmployees->LockType = adLockBatchOptimistic;
pRstEmployees->UpdateBatch(adAffectCurrent);
EditModeOutput("After Update: ", pRstEmployees->EditMode);
pRstEmployees->Fields->Item["fname"]->Value = (_bstr_t)("test");
EditModeOutput("After Edit: ", pRstEmployees->EditMode);
switch (intEditMode) {
case adEditNone :
printf("adEditNone");
break;
case adEditInProgress :
printf("adEditInProgress");
break;
case adEditAdd :
printf("adEditAdd");
break;
}
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("\n\t Error number: %x\t%s\n", pErr->Number, (LPCSTR)pErr->Description);
}
}
}
After AddNew:
EditMode = adEditAdd
After Update:
EditMode = adEditNone
After Edit:
EditMode = adEditInProgress
See Also
CursorType Property (ADO )
EditMode Property
LockType Property (ADO )
Recordset Object (ADO )
Property Object (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
ADO objects have two types of properties: built-in and dynamic.
Built-in properties are those properties implemented in ADO and immediately available to any new object,
using the MyObject.Property syntax. They do not appear as Property objects in an object's Properties
collection, so although you can change their values, you cannot modify their characteristics.
Dynamic properties are defined by the underlying data provider, and appear in the Properties collection for
the appropriate ADO object. For example, a property specific to the provider may indicate if a Recordset object
supports transactions or updating. These additional properties will appear as Property objects in that
Recordset object's Properties collection. Dynamic properties can be referenced only through the collection,
using the MyObject.Properties(0) or MyObject.Properties("Name") syntax.
You cannot delete either kind of property.
A dynamic Property object has four built-in properties of its own:
The Name property is a string that identifies the property.
The Type property is an integer that specifies the property data type.
The Value property is a variant that contains the property setting. Value is the default property for a
Property object.
The Attributes property is a long value that indicates characteristics of the property specific to the
provider.
This section contains the following topic.
Property Object Properties, Methods, and Events
See Also
Command Object (ADO )
Connection Object (ADO )
Field Object
Properties Collection (ADO )
Recordset Object (ADO )
FilterGroupEnum
11/28/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.FilterGroup.AFFECTEDRECORDS
AdoEnums.FilterGroup.CONFLICTINGRECORDS
AdoEnums.FilterGroup.FETCHEDRECORDS
AdoEnums.FilterGroup.NONE
AdoEnums.FilterGroup.PENDINGRECORDS
Applies To
Filter Property
LoadFromFile Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Stream.LoadFromFileFileName
Parameters
FileName
A String value that contains the name of a file to be loaded into the Stream. FileName can contain any valid path
and name in UNC format. If the specified file does not exist, a run-time error occurs.
Remarks
This method can be used to load the contents of a local file into a Stream object. This can be used to upload the
contents of a local file to a server.
The Stream object must be already open before calling LoadFromFile. This method does not change the binding
of the Stream object; it will still be bound to the object specified by the URL or Record with which the Stream
was originally opened.
LoadFromFile overwrites the current contents of the Stream object with data read from the file. Any existing
bytes in the Stream are overwritten by the contents of the file. Any previously existing and remaining bytes
following the EOS created by LoadFromFile, are truncated.
After a call to LoadFromFile, the current position is set to the beginning of the Stream (Position is 0).
Because 2 bytes may be added to the beginning of the stream for encoding, the size of the stream may not exactly
match the size of the file from which it was loaded.
Applies To
Stream Object (ADO )
NextRecordset Method Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the NextRecordset method to view the data in a recordset that uses a compound command
statement made up of three separate SELECT statements.
'BeginNextRecordsetVB
Do Until rstCompound.EOF
Debug.Print , rstCompound.Fields(0), rstCompound.Fields(1)
rstCompound.MoveNext
Loop
' clean up
Cnxn.Close
Set rstCompound = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstCompound Is Nothing Then
If rstCompound.State = adStateOpen Then rstCompound.Close
End If
Set rstCompound = Nothing
Set rstCompound = Nothing
See Also
NextRecordset Method (ADO )
Recordset Object (ADO )
Field Object
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Each Field object corresponds to a column in the Recordset. You use the Value property of Field
objects to set or return data for the current record. Depending on the functionality the provider exposes,
some collections, methods, or properties of a Field object may not be available.
With the collections, methods, and properties of a Field object, you can do the following:
Return the name of a field with the Name property.
View or change the data in the field with the Value property. Value is the default property of the
Field object.
Return the basic characteristics of a field with the Type, Precision, and NumericScale properties.
Return the declared size of a field with the DefinedSize property.
Return the actual size of the data in a given field with the ActualSize property.
Determine what types of functionality are supported for a given field with the Attributes
property and Properties collection.
Manipulate the values of fields containing long binary or long character data with the
AppendChunk and GetChunk methods.
If the provider supports batch updates, resolve discrepancies in field values during batch
updating with the OriginalValue and UnderlyingValue properties.
All of the metadata properties ( Name, Type, DefinedSize, Precision, and NumericScale) are
available before opening the Field object's Recordset. Setting them at that time is useful for
dynamically constructing forms.
This section contains the following topic.
Field Object Properties, Methods, and Events
See Also
Fields Collection (ADO )
Properties Collection (ADO )
Recordset Object (ADO )
Recordset (ADO for Visual C++ Syntax)
10/1/2018 • 2 minutes to read • Edit Online
Methods
AddNew(VARIANT FieldList, VARIANT Values)
Cancel(void)
CancelBatch(AffectEnum AffectRecords)
CancelUpdate(void)
Clone(LockTypeEnum LockType, _ADORecordset **ppvObject)
Close(void)
CompareBookmarks(VARIANT Bookmark1, VARIANT Bookmark2, CompareEnum *pCompare)
Delete(AffectEnum AffectRecords)
Find(BSTR Criteria, LONG SkipRecords, SearchDirectionEnum SearchDirection, VARIANT Start)
GetRows(long Rows, VARIANT Start, VARIANT Fields, VARIANT *pvar)
GetString(StringFormatEnum StringFormat, long NumRows, BSTR ColumnDelimeter, BSTR RowDelimeter, BSTR NullExpr,
BSTR *pRetString)
Move(long NumRecords, VARIANT Start)
MoveFirst(void)
MoveLast(void)
MoveNext(void)
MovePrevious(void)
NextRecordset(VARIANT *RecordsAffected, _ADORecordset **ppiRs)
Open(VARIANT Source, VARIANT ActiveConnection, CursorTypeEnum CursorType, LockTypeEnum LockType, LONG Options)
Requery(LONG Options)
Resync(AffectEnum AffectRecords, ResyncEnum ResyncValues)
Save(BSTR FileName, PersistFormatEnum PersistFormat)
Supports(CursorOptionEnum CursorOptions, VARIANT_BOOL *pb)
Update(VARIANT Fields, VARIANT Values)
UpdateBatch(AffectEnum AffectRecords)
Properties
get_AbsolutePage(PositionEnum *pl)
put_AbsolutePage(PositionEnum Page)
get_AbsolutePosition(PositionEnum *pl)
put_AbsolutePosition(PositionEnum Position)
get_ActiveCommand(IDispatch **ppCmd)
get_ActiveConnection(VARIANT *pvar)
put_ActiveConnection(VARIANT vConn)
putref_ActiveConnection(IDispatch *pconn)
get_BOF(VARIANT_BOOL *pb)
get_Bookmark(VARIANT *pvBookmark)
put_Bookmark(VARIANT vBookmark)
get_CacheSize(long *pl)
put_CacheSize(long CacheSize)
get_CursorLocation(CursorLocationEnum *plCursorLoc)
put_CursorLocation(CursorLocationEnum lCursorLoc)
get_CursorType(CursorTypeEnum *plCursorType)
put_CursorType(CursorTypeEnum lCursorType)
get_DataMember(BSTR *pbstrDataMember)
put_DataMember(BSTR bstrDataMember)
get_DataSource(IUnknown **ppunkDataSource)
putref_DataSource(IUnknown *punkDataSource)
get_EditMode(EditModeEnum *pl)
get_EOF(VARIANT_BOOL *pb)
get_Filter(VARIANT *Criteria)
put_Filter(VARIANT Criteria)
get_LockType(LockTypeEnum *plLockType)
put_LockType(LockTypeEnum lLockType)
get_MarshalOptions(MarshalOptionsEnum *peMarshal)
put_MarshalOptions(MarshalOptionsEnum eMarshal)
get_MaxRecords(long *plMaxRecords)
put_MaxRecords(long lMaxRecords)
get_PageCount(long *pl)
get_PageSize(long *pl)
put_PageSize(long PageSize)
get_RecordCount(long *pl)
get_Sort(BSTR *Criteria)
put_Sort(BSTR Criteria)
get_Source(VARIANT *pvSource)
put_Source(BSTR bstrConn)
putref_Source(IDispatch *pcmd)
get_State(LONG *plObjState)
get_Status(long *pl)
get_StayInSync(VARIANT_BOOL *pbStayInSync)
put_StayInSync(VARIANT_BOOL bStayInSync)
get_Fields(ADOFields **ppvObject)
Events
EndOfRecordset(VARIANT_BOOL *fMoreData, EventStatusEnum *adStatus, _ADORecordset *pRecordset)
FetchComplete(ADOError *pError, EventStatusEnum *adStatus, _ADORecordset *pRecordset)
FetchProgress(long Progress, long MaxProgress, EventStatusEnum *adStatus, _ADORecordset *pRecordset)
FieldChangeComplete(LONG cFields, VARIANT Fields, ADOError *pError, EventStatusEnum *adStatus, _ADORecordset
*pRecordset)
MoveComplete(EventReasonEnum adReason, ADOError *pError, EventStatusEnum *adStatus, _ADORecordset *pRecordset)
RecordChangeComplete(EventReasonEnum adReason, LONG cRecords, ADOError *pError, EventStatusEnum *adStatus,
_ADORecordset *pRecordset)
RecordsetChangeComplete(EventReasonEnum adReason, ADOError *pError, EventStatusEnum *adStatus, _ADORecordset
*pRecordset)
WillChangeField(LONG cFields, VARIANT Fields, EventStatusEnum *adStatus, _ADORecordset *pRecordset)
WillChangeRecord(EventReasonEnum adReason, LONG cRecords, EventStatusEnum *adStatus, _ADORecordset
*pRecordset)
WillChangeRecordset(EventReasonEnum adReason, EventStatusEnum *adStatus, _ADORecordset *pRecordset)
WillMove(EventReasonEnum adReason, EventStatusEnum *adStatus, _ADORecordset *pRecordset)
See Also
Recordset Object (ADO )
MaxRecords Property Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the MaxRecords property to open a Recordset containing the 10 most expensive titles in the
Titles table.
Example
// MaxRecords_Property_Example.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF","EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
#include "icrsint.h"
// This class extracts titles and type from the titles table
class CTitleRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CTitleRs)
END_ADO_BINDING()
public:
CHAR m_szau_Title[81];
ULONG lau_TitleStatus;
DOUBLE m_szau_Price;
ULONG lau_PriceStatus;
};
// Function Declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void MaxRecordsX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
MaxRecordsX();
::CoUninitialize();
}
void MaxRecordsX() {
// Define ADO ObjectPointers. Initialize Pointers on define
// These are in the ADODB :: namespace
_RecordsetPtr pRstTemp = NULL;
// Open Recordset containing the 10 most expensive titles in the Titles table.
TESTHR(pRstTemp.CreateInstance(__uuidof(Recordset)));
pRstTemp->MaxRecords = 10;
while ( !(pRstTemp->EndOfFile) ) {
printf("%s --- %6.2lf\n", titlers.lau_TitleStatus == adFldOK ?
titlers.m_szau_Title : "<NULL>", titlers.lau_PriceStatus == adFldOK ?
titlers.m_szau_Price : 0.00);
pRstTemp->MoveNext();
}
}
catch(_com_error &e) {
// Display errors, if any. Pass connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstTemp->GetActiveConnection();
if (pRstTemp)
if (pRstTemp->State == adStateOpen)
pRstTemp->Close();
};
if ( (pConnection->Errors->Count)>0 ) {
long nCount = pConnection->Errors->Count;
See Also
MaxRecords Property (ADO )
Recordset Object (ADO )
ADO Code Examples in Visual C++
10/1/2018 • 2 minutes to read • Edit Online
Use the following code examples to learn how to use the ADO methods, properties, and events when writing in
Microsoft Visual C++.
NOTE
Paste the entire code example, from beginning to end, into your code editor. The example may not run correctly if partial
examples are used or if paragraph formatting is lost.
Methods
AddNew Method Example
Append and CreateParameter Methods Example
AppendChunk and GetChunk Methods Example
BeginTrans, CommitTrans, and RollbackTrans Methods Example
Cancel Method Example
Clone Method Example
CompareBookmarks Method Example
Delete Method Example
Execute, Requery, and Clear Methods Example
Find Method Example
GetRows Method Example
GetString Method Example
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods Example
NextRecordset Method Example
Open and Close Methods Example
OpenSchema Method Example
Refresh Method Example
Resync Method Example
Save and Open Methods Example
Seek Method and Index Property Example
Supports Method Example
Update and CancelUpdate Methods Example
UpdateBatch and CancelBatch Methods Example
Properties
AbsolutePage, PageCount, and PageSize Properties Example
AbsolutePosition and CursorLocation Properties Example
ActiveCommand Property Example
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties
Example
ActualSize and DefinedSize Properties Example
Attributes and Name Properties Example
BOF, EOF, and Bookmark Properties Example
CacheSize Property Example
ConnectionString, ConnectionTimeout, and State Properties Example
Count Property Example
CursorType, LockType, and EditMode Properties Example
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example
Filter and RecordCount Properties Example
Index Property and Seek Method Example
IsolationLevel and Mode Properties Example
Item Property Example
MarshalOptions Property Example
MaxRecords Property Example
NumericScale and Precision Properties Example
Optimize Property Example
OriginalValue and UnderlyingValue Properties Example
Prepared Property Example
Provider and DefaultDatabase Properties Example
Sort Property Example
Source Property Example
State Property Example
Status Property Example
StayInSync Property Example
Type Property Example (Fields)
Type Property Example (Property)
Value Property Example
Version Property Example
Other
ADO Events Model Example
See Also
ADO Code Examples in Visual Basic
ADO Code Examples VBScript
Appendix D: ADO Samples
MarshalOptions Property Example (VB)
11/28/2018 • 2 minutes to read • Edit Online
This example uses the MarshalOptions property to specify what rows are sent back to the server - All Rows or only
Modified Rows.
'BeginMarshalOptionsVB
' clean up
rstEmployees.Close
Cnxn.Close
Set rstEmployees = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstEmployees Is Nothing Then
If rstEmployees.State = adStateOpen Then rstEmployees.Close
End If
Set rstEmployees = Nothing
See Also
MarshalOptions Property (ADO )
MarshalOptionsEnum
GetRowsOptionEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.GetRowsOption.REST
Applies To
GetRows Method (ADO )
Find Method Example (JScript)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Recordset object's Find method to locate and display the companies in the Northwind
database whose name begins with the letter G. Cut and paste the following code to Notepad or another text editor,
and save it as FindJS.asp.
<html>
<head>
<title>ADO Recordset.Find Example</title>
<style>
<!--
BODY {
font-family: 'Verdana','Arial','Helvetica',sans-serif;
BACKGROUND-COLOR:white;
COLOR:black;
}
.thead {
background-color: #008080;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
color: white;
}
.thead2 {
background-color: #800000;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
color: white;
}
.tbody {
text-align: center;
background-color: #f7efde;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
}
-->
</style>
</head>
<body bgcolor="white">
try
{
// open connection
Cnxn.Open(strCnxn);
Cnxn.Open(strCnxn);
rsCustomers.ActiveConnection = Cnxn;
rsCustomers.CursorLocation = adUseClient;
rsCustomers.CursorType = adOpenKeyset;
rsCustomers.LockType = adLockOptimistic;
rsCustomers.Source = SQLCustomers;
rsCustomers.Open();
rsCustomers.MoveFirst();
//find criteria
strFind = "CompanyName like 'g%'"
rsCustomers.Find(strFind);
if (rsCustomers.EOF) {
Response.Write("No records matched ");
Response.Write(SQLCustomers & "So cannot make table...");
Cnxn.Close();
Response.End();
}
else {
Response.Write('<table width="100%" border="2">');
Response.Write('<tr class="thead2">');
// Put Headings On The Table for each Field Name
for (thisField = 0; thisField < rsCustomers.Fields.Count; thisField++) {
fieldObject = rsCustomers.Fields(thisField);
Response.Write('<th width="' + Math.floor(100 / rsCustomers.Fields.Count) + '%">' +
fieldObject.Name + "</th>");
}
Response.Write("</tr>");
while (!rsCustomers.EOF) {
Response.Write('<tr class="tbody">');
for(thisField=0; thisField<rsCustomers.Fields.Count; thisField++) {
fieldObject = rsCustomers.Fields(thisField);
strField = fieldObject.Value;
if (strField == null)
strField = "-Null-";
if (strField == "")
strField = "";
Response.Write("<td>" + strField + "</td>");
}
rsCustomers.Find(strFind, 1, adSearchForward)
Response.Write("</tr>");
}
Response.Write("</table>");
}
}
catch (e)
{
Response.Write(e.message);
}
finally
{
// clean up
if (rsCustomers.State == adStateOpen)
rsCustomers.Close;
if (Cnxn.State == adStateOpen)
Cnxn.Close;
rsCustomers = null;
Cnxn = null;
}
%>
</body>
</html>
<!-- EndFindJS -->
See Also
Find Method (ADO )
Recordset Object (ADO )
Execute, Requery, and Clear Methods Example
(VC++)
10/1/2018 • 3 minutes to read • Edit Online
This example demonstrates the Execute method when run from both a Command object and a Connection
object. It also uses the Requery method to retrieve current data in a recordset, and the Clear method to clear the
contents of the Errors collection. The ExecuteCommand and PrintOutput functions are required for this example
to run.
// Execute_Requery_Clear_Method_Sample.cpp
// compile with: /EHsc
#include <ole2.h>
#include <stdio.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void ExecuteX();
void ExecuteCommand(_CommandPtr pCmdTemp, _RecordsetPtr pRstTemp);
void PrintOutput(_RecordsetPtr pRstTemp);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
ExecuteX();
::CoUninitialize();
}
void ExecuteX() {
// Define string variables.
_bstr_t strSQLChange("UPDATE Titles SET Type = 'self_help' WHERE Type = 'psychology'");
_bstr_t strSQLRestore("UPDATE Titles SET Type = 'psychology' WHERE Type = 'self_help'");
_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");
try {
// Open connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open (strCnn, "", "", adConnectUnspecified);
// Use Connection object's Execute method to execute SQL statement to restore data.
pConnection->Execute(strSQLRestore, NULL, adExecuteNoRecords);
catch(_com_error &e) {
// Notify user of any errors that result from executing the query.
// Pass a connection pointer accessed from the Recordset.
PrintProviderError(pRstTemp->GetActiveConnection());
PrintComError(e);
}
}
pRstTemp->MoveNext();
}
}
}
if ( (pConnection->Errors->Count) > 0 ) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number, pErr->Description);
}
}
}
See Also
Clear Method (ADO )
Command Object (ADO )
Connection Object (ADO )
Errors Collection (ADO )
Execute Method (ADO Command)
Execute Method (ADO Connection)
Requery Method
IDSOShapeExtensions Interface
10/1/2018 • 2 minutes to read • Edit Online
Gets the underlying OLE DB Data Source object for the SHAPE provider.
Syntax
interface IDSOShapeExtensions: public IUnknown {
public:
HRESULT GetDataProviderDSO(
IUnknown **ppDataProviderDSOIUnknown
);
};
Methods
GetDataProviderDSO Method Retrieves the underlying OLE DB Data Source object from the
Shape provider.
Requirements
Version: ADO 2.0 and later
Library: msado15.dll
UUID: 00000283-0000-0010-8000-00AA006D2EA4
Clone Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Creates a duplicate Recordset object from an existing Recordset object. Optionally, specifies that the clone be
read-only.
Syntax
Set rstDuplicate = rstOriginal.Clone (LockType)
Return Value
Returns a Recordset object reference.
Parameters
rstDuplicate
An object variable that identifies the duplicate Recordset object to be created.
rstOriginal
An object variable that identifies the Recordset object to be duplicated.
LockType
Optional. A LockTypeEnum value that specifies either the lock type of the original Recordset, or a read-only
Recordset. Valid values are adLockUnspecified or adLockReadOnly.
Remarks
Use the Clone method to create multiple, duplicate Recordset objects, especially if you want to maintain more
than one current record in a given set of records. Using the Clone method is more efficient than creating and
opening a new Recordset object that uses the same definition as the original.
The Filter property of the original Recordset, if any, will not be applied to the clone. Set the Filter property of the
new Recordset to filter the results. The simplest way to copy any existing Filter value is to assign it directly, as
follows.
rsNew.Filter = rsOriginal.Filter
The current record of a newly created clone is set to the first record.
Changes you make to one Recordset object are visible in all of its clones regardless of cursor type. However,
after you execute Requery on the original Recordset, the clones will no longer be synchronized to the original.
Closing the original Recordset does not close its copies, nor does closing a copy close the original or any of the
other copies.
You can only clone a Recordset object that supports bookmarks. Bookmark values are interchangeable; that is, a
bookmark reference from one Recordset object refers to the same record in any of its clones.
Some Recordset events that are triggered will also occur in all Recordset clones. However, because the current
record can differ between cloned Recordsets, the events may not be valid for the clone. For example, if you
change a value of a field, a WillChangeField event will occur in the changed Recordset and in all clones. The
Fields parameter of the WillChangeField event of a cloned Recordset (where the change was not made) will
refer to the fields of the current record of the clone, which may be a different record than the current record of the
original Recordset where the change occurred.
The following table provides a full listing of all Recordset events. It indicates whether they are valid and triggered
for any recordset clones generated by using the Clone method.
EndOfRecordset No
FetchComplete No
FetchProgress No
FieldChangeComplete Yes
MoveComplete No
RecordChangeComplete Yes
RecordsetChangeComplete No
WillChangeField Yes
WillChangeRecord Yes
WillChangeRecordset No
WillMove No
Applies To
Recordset Object (ADO )
See Also
Clone Method Example (VB )
Clone Method Example (VBScript)
Clone Method Example (VC++)
Type Property Example (Field) (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Type property by displaying the name of the constant that corresponds to the
value of the Type property of all the Field objects in the Employees table. The FieldType function is required for
this procedure to run.
'BeginTypeFieldVB
Public Sub Main()
On Error GoTo ErrorHandler
' clean up
rstEmployees.Close
Cnxn.Close
Set rstEmployees = Nothing
Set Cnxn = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstEmployees Is Nothing Then
If rstEmployees.State = adStateOpen Then rstEmployees.Close
End If
Set rstEmployees = Nothing
See Also
Field Object
Type Property (ADO )
Attributes Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the Attributes property to set or return characteristics of Connection objects, Parameter objects, Field
objects, or Property objects.
When you set multiple attributes, you can sum the appropriate constants. If you set the property value to a
sum including incompatible constants, an error occurs.
NOTE
Remote Data Service Usage This property is not available on a client-side Connection object.
Applies To
See Also
Attributes and Name Properties Example (VB )
Attributes and Name Properties Example (VC++)
AppendChunk Method (ADO )
BeginTrans, CommitTrans, and RollbackTrans Methods (ADO )
GetChunk Method (ADO )
CursorLocationEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.CursorLocation.CLIENT
AdoEnums.CursorLocation.NONE
AdoEnums.CursorLocation.SERVER
Applies To
CursorLocation Property (ADO )
Resync Method Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates using the Resync method to refresh data in a static recordset.
'BeginResyncVB
strSQLTitles = "titles"
rstTitles.Open strSQLTitles
' clean up
rstTitles.CancelBatch
rstTitles.Close
Cnxn.Close
Set rstTitles = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
' clean up
If Not rstTitles Is Nothing Then
If rstTitles.State = adStateOpen Then
rstTitles.CancelBatch
rstTitles.Close
End If
End If
Set rstTitles = Nothing
See Also
Recordset Object (ADO )
Resync Method
Open Method (ADO Record)
10/1/2018 • 2 minutes to read • Edit Online
Opens an existing Record object, or creates a new item represented by the Record, such as a file or directory.
Syntax
Open Source, ActiveConnection, Mode, CreateOptions, Options, UserName, Password
Parameters
Source
Optional. A Variant that may represent the URL of the entity to be represented by this Record object, a
Command, an open Recordset or another Record object, a string that contains an SQL SELECT statement or a
table name.
ActiveConnection
Optional. A Variant that represents the connect string or open Connection object.
Mode
Optional. A ConnectModeEnum value that specifies the access mode for the resultant Record object. Default
value is adModeUnknown.
CreateOptions
Optional. A RecordCreateOptionsEnum value that specifies whether an existing file or directory should be
opened, or a new file or directory should be created. Default value is adFailIfNotExists. If set to the default
value, the access mode is obtained from the Mode property. This parameter is ignored when the Source
parameter does not contain a URL.
Options
Optional. A RecordOpenOptionsEnum value that specifies options for opening the Record. Default value is
adOpenRecordUnspecified. These values can be combined.
UserName
Optional. A String value that contains the user ID that, if it is required, authorizes access to Source.
Password
Optional. A String value that contains the password that, if it is required, verifies UserName.
Remarks
Source may be:
A URL. If the protocol for the URL is http, the Internet Provider will be invoked by default. If the URL
points to a node that contains an executable script (such as an .ASP page), a Record that contains the
source instead of the executed contents is opened by default. Use the Options argument to modify this
behavior.
A Record object. A Record object opened from another Record will clone the original Record object.
A Command object. The opened Record object represents the single row returned by executing the
Command. If the results contain more than a single row, the contents of the first row are placed in the
record and an error may be added to the Errors collection.
An SQL SELECT statement. The opened Record object represents the single row returned by executing
the contents of the string. If the results contain more than a single row, the contents of the first row are
placed in the record and an error may be added to the Errors collection.
A table name.
If the Record object represents an entity that cannot be accessed with a URL (for example, a row of a Recordset
derived from a database), the values of both the ParentURL property and the field accessed with the
adRecordURL constant are null.
NOTE
URLs using the http scheme will automatically invoke the Microsoft OLE DB Provider for Internet Publishing. For more
information, see Absolute and Relative URLs.
Applies To
Record Object (ADO )
See Also
Open Method (ADO Connection)
Open Method (ADO Recordset)
Open Method (ADO Stream)
OpenSchema Method
NextRecordset Method (ADO)
10/10/2018 • 2 minutes to read • Edit Online
Clears the current Recordset object and returns the next Recordset by advancing through a series of commands.
Syntax
Set recordset2 = recordset1.NextRecordset(RecordsAffected )
Return Value
Returns a Recordset object. In the syntax model, recordset1 and recordset2 can be the same Recordset object, or
you can use separate objects. When using separate Recordset objects, resetting the ActiveConnection property
on the original Recordset (recordset1) after NextRecordset has been called will generate an error.
Parameters
RecordsAffected
Optional. A Long variable to which the provider returns the number of records that the current operation
affected.
NOTE
This parameter only returns the number of records affected by an operation; it does not return a count of records from a
select statement used to generate the Recordset.
Remarks
Use the NextRecordset method to return the results of the next command in a compound command statement
or of a stored procedure that returns multiple results. If you open a Recordset object based on a compound
command statement (for example, "SELECT * FROM table1;SELECT * FROM table2") using the Execute method
on a Command or the Open method on a Recordset, ADO executes only the first command and returns the
results to recordset. To access the results of subsequent commands in the statement, call the NextRecordset
method.
As long as there are additional results and the Recordset containing the compound statements is not
disconnected or marshaled across process boundaries, the NextRecordset method will continue to return
Recordset objects. If a row -returning command executes successfully but returns no records, the returned
Recordset object will be open but empty. Test for this case by verifying that the BOF and EOF properties are
both True. If a non-row -returning command executes successfully, the returned Recordset object will be closed,
which you can verify by testing the State property on the Recordset. When there are no more results, recordset
will be set to Nothing.
The NextRecordset method is not available on a disconnected Recordset object, where ActiveConnection has
been set to Nothing (in Microsoft Visual Basic) or NULL (in other languages).
If an edit is in progress while in immediate update mode, calling the NextRecordset method generates an error;
call the Update or CancelUpdate method first.
To pass parameters for more than one command in the compound statement by filling the Parameters collection,
or by passing an array with the original Open or Execute call, the parameters must be in the same order in the
collection or array as their respective commands in the command series. You must finish reading all the results
before reading output parameter values.
Your OLE DB provider determines when each command in a compound statement is executed. The Microsoft
OLE DB Provider for SQL Server, for example, executes all commands in a batch upon receiving the compound
statement. The resulting Recordsets are simply returned when you call NextRecordset.
However, other providers may execute the next command in a statement only after NextRecordset is called. For
these providers, if you explicitly close the Recordset object before stepping through the entire command
statement, ADO never executes the remaining commands.
Applies To
Recordset Object (ADO )
See Also
NextRecordset Method Example (VB )
NextRecordset Method Example (VC++)
BeginTrans, CommitTrans, and RollbackTrans
Methods Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example changes the book type of all psychology books in the Titles table of the database. After the
BeginTrans method starts a transaction that isolates all the changes made to the Titles table, the CommitTrans
method saves the changes. You can use the RollbackTrans method to undo changes that you saved using the
Update method.
'BeginBeginTransVB
Cnxn.BeginTrans
rstTitles.MoveFirst
Do Until rstTitles.EOF
If Trim(rstTitles!Type) = "psychology" Then
strTitle = rstTitles!Title
strMessage = "Title: " & strTitle & vbCr & _
"Change type to self help?"
Do Until rstTitles.EOF
If Trim(rstTitles!Type) = "self_help" Then
rstTitles!Type = "psychology"
rstTitles.Update
End If
rstTitles.MoveNext
Loop
' clean up
rstTitles.Close
Cnxn.Close
Set rstTitles = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstTitles Is Nothing Then
If rstTitles.State = adStateOpen Then rstTitles.Close
End If
Set rstTitles = Nothing
'EndBeginTransVB
See Also
BeginTrans, CommitTrans, and RollbackTrans Methods (ADO )
Connection Object (ADO )
AddNew Method (ADO)
10/1/2018 • 3 minutes to read • Edit Online
Syntax
recordset.AddNew FieldList, Values
Parameters
recordset
A Recordset object.
FieldList
Optional. A single name, or an array of names or ordinal positions of the fields in the new record.
Values
Optional. A single value, or an array of values for the fields in the new record. If Fieldlist is an array, Values
must also be an array with the same number of members; otherwise, an error occurs. The order of field names
must match the order of field values in each array.
Remarks
Use the AddNew method to create and initialize a new record. Use the Supports method with adAddNew (a
CursorOptionEnum value) to verify whether you can add records to the current Recordset object.
After you call the AddNew method, the new record becomes the current record and remains current after you
call the Update method. Since the new record is appended to the Recordset, a call to MoveNext following the
Update will move past the end of the Recordset, making EOF True. If the Recordset object does not support
bookmarks, you may not be able to access the new record once you move to another record. Depending on
your cursor type, you may need to call the Requery method to make the new record accessible.
If you call AddNew while editing the current record or while adding a new record, ADO calls the Update
method to save any changes and then creates the new record.
The behavior of the AddNew method depends on the updating mode of the Recordset object and whether
you pass the Fieldlist and Values arguments.
In immediate update mode (in which the provider writes changes to the underlying data source once you call
the Update method), calling the AddNew method without arguments sets the EditMode property to
adEditAdd (an EditModeEnum value). The provider caches any field value changes locally. Calling the
Update method posts the new record to the database and resets the EditMode property to adEditNone (an
EditModeEnum value). If you pass the Fieldlist and Values arguments, ADO immediately posts the new
record to the database (no Update call is necessary); the EditMode property value does not change
(adEditNone).
In batch update mode (in which the provider caches multiple changes and writes them to the underlying data
source only when you call the UpdateBatch method), calling the AddNew method without arguments sets the
EditMode property to adEditAdd. The provider caches any field value changes locally. Calling the Update
method adds the new record to the current Recordset, but the provider does not post the changes to the
underlying database, or reset the EditMode to adEditNone, until you call the UpdateBatch method. If you
pass the Fieldlist and Values arguments, ADO sends the new record to the provider for storage in a cache and
sets the EditMode to adEditAdd; you need to call the UpdateBatch method to post the new record to the
underlying database.
Example
The following example shows how to use the AddNew method with the field list and value list included, to see
how to include the field list and value list as arrays.
cn.Open
rs.Open "select * from xxx..aa1", cn, adOpenKeyset, adLockOptimistic
Applies To
Recordset Object (ADO )
See Also
AddNew Method Example (VB )
AddNew Method Example (VBScript)
AddNew Method Example (VC++)
CancelUpdate Method (ADO )
EditMode Property
Requery Method
Supports Method
Update Method
UpdateBatch Method
MoveFirst, MoveLast, MoveNext, and
MovePrevious Methods (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Moves to the first, last, next, or previous record in a specified Recordset object and makes that record the
current record.
Syntax
recordset.{MoveFirst | MoveLast | MoveNext | MovePrevious}
Remarks
Use the MoveFirst method to move the current record position to the first record in the Recordset.
Use the MoveLast method to move the current record position to the last record in the Recordset. The
Recordset object must support bookmarks or backward cursor movement; otherwise, the method call will
generate an error.
A call to either MoveFirst or MoveLast when the Recordset is empty (both BOF and EOF are True)
generates an error.
Use the MoveNext method to move the current record position one record forward (toward the bottom of
the Recordset). If the last record is the current record and you call the MoveNext method, ADO sets the
current record to the position after the last record in the Recordset (EOF is True). An attempt to move
forward when the EOF property is already True generates an error.
In ADO 2.5 and later, when the Recordset has been filtered or sorted and the data of the current record is
changed, calling the MoveNext method moves the cursor two records forward from the current record. This
is because when the current record is changed, the next record becomes the new current record. Calling
MoveNext after the change moves the cursor one record forward from the new current record. This is
different from the behavior in ADO 2.1 and earlier. In these earlier versions, changing the data of a current
record in the sorted or filtered Recordset does not change the position of the current record, and MoveNext
moves the cursor to the next record immediately after the current record.
Use the MovePrevious method to move the current record position one record backward (toward the top of
the Recordset). The Recordset object must support bookmarks or backward cursor movement; otherwise,
the method call will generate an error. If the first record is the current record and you call the MovePrevious
method, ADO sets the current record to the position before the first record in the Recordset (BOF is True). An
attempt to move backward when the BOF property is already True generates an error. If the Recordset object
does not support either bookmarks or backward cursor movement, the MovePrevious method will generate
an error.
If the Recordset is forward only and you want to support both forward and backward scrolling, you can use
the CacheSize property to create a record cache that will support backward cursor movement through the
Move method. Because cached records are loaded into memory, you should avoid caching more records than
is necessary. You can call the MoveFirst method in a forward-only Recordset object; doing so may cause the
provider to re-execute the command that generated the Recordset object.
Applies To
Recordset Object (ADO )
See Also
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods Example (VB )
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods Example (VBScript)
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods Example (VC++)
Move Method (ADO )
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods (RDS )
MoveRecord Method (ADO )
Type Property Example (Property) (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Type property. It is a model of a utility for listing the names and types of a
collection, like Properties, Fields, etc.
We do not need to open the Recordset to access its Properties collection; they come into existence when the
Recordset object is instantiated. However, setting the CursorLocation property to adUseClient adds several
dynamic properties to the Recordset object's Properties collection, making the example a little more interesting.
For sake of illustration, we explicitly use the Item property to access each Property object.
// BeginTypePropertyCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
// Function declarations
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void TypeX();
void PrintComError(_com_error &e);
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
TypeX();
::CoUninitialize();
}
void TypeX() {
// Define ADO object pointers, initialize pointers. These are in the ADODB:: namespace
_RecordsetPtr pRst = NULL;
PropertyPtr pProperty = NULL;
try {
TESTHR(pRst.CreateInstance (__uuidof(Recordset)));
switch(propType) {
case adBigInt:
strMsg = "adBigInt";
break;
case adBinary:
strMsg = "adBinary";
break;
case adBoolean:
strMsg = "adBoolean";
break;
case adBSTR:
case adBSTR:
strMsg = "adBSTR";
break;
case adChapter:
strMsg = "adChapter";
break;
case adChar:
strMsg = "adChar";
break;
case adCurrency:
strMsg = "adCurrency";
break;
case adDate:
strMsg = "adDate";
break;
case adDBDate:
strMsg = "adDBDate";
break;
case adDBTime:
strMsg = "adDBTime";
break;
case adDBTimeStamp:
strMsg = "adDBTimeStamp";
break;
case adDecimal:
strMsg = "adDecimal";
break;
case adDouble:
strMsg = "adDouble";
break;
case adEmpty:
strMsg = "adEmpty";
break;
case adError:
strMsg = "adError";
break;
case adFileTime:
strMsg = "adFileTime";
break;
case adGUID:
strMsg = "adGUID";
break;
case adIDispatch:
strMsg = "adIDispatch";
break;
case adInteger:
strMsg = "adInteger";
break;
case adIUnknown:
strMsg = "adIUnknown";
break;
case adLongVarBinary:
strMsg = "adLongVarBinary";
break;
case adLongVarChar:
strMsg = "adLongVarChar";
break;
case adLongVarWChar:
strMsg = "adLongVarWChar";
break;
case adNumeric:
strMsg = "adNumeric";
break;
case adPropVariant:
strMsg = "adPropVariant";
break;
case adSingle:
strMsg = "adSingle";
break;
case adSmallInt:
case adSmallInt:
strMsg = "adSmallInt";
break;
case adTinyInt:
strMsg = "adTinyInt";
break;
case adUnsignedBigInt:
strMsg = "adUnsignedBigInt";
break;
case adUnsignedInt:
strMsg = "adUnsignedInt";
break;
case adUnsignedSmallInt:
strMsg = "adUnsignedSmallInt";
break;
case adUnsignedTinyInt:
strMsg = "adUnsignedTinyInt";
break;
case adUserDefined:
strMsg = "adUserDefined";
break;
case adVarBinary:
strMsg = "adVarBinary";
break;
case adVarChar:
strMsg = "adVarChar";
break;
case adVariant:
strMsg = "adVariant";
break;
case adVarNumeric:
strMsg = "adVarNumeric";
break;
case adVarWChar:
strMsg = "adVarWChar";
break;
case adWChar:
strMsg = "adWChar";
break;
default:
strMsg = "*UNKNOWN*";
break;
}
intLineCnt++;
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
Remarks
An index can improve the performance of operations that find or sort values in a Recordset. The index is internal
to ADO; you cannot explicitly access or use it in your application.
To create an index on a field, set the Optimize property to True. To delete the index, set this property to False.
Optimize is a dynamic property appended to the Field object Properties collection when the CursorLocation
property is set to adUseClient.
Usage
Dim rs As New Recordset
Dim fld As Field
rs.CursorLocation = adUseClient 'Enable index creation
rs.Fields.Append "Field1", adChar, 35, adFldIsNullable
rs.Open
Set fld = rs.Fields(0)
fld.Properties("Optimize") = True 'Create an index
fld.Properties("Optimize") = False 'Delete an index
Applies To
Field Object
See Also
Optimize Property Example (VB )
Optimize Property Example (VC++)
Filter Property
Find Method (ADO )
Sort Property
Size Property (ADO Stream)
10/1/2018 • 2 minutes to read • Edit Online
Return Values
Returns a Long value that specifies the size of the stream in number of bytes. The default value is the size of the
stream, or -1 if the size of the stream is not known.
Remarks
Size can be used only with open Stream objects.
NOTE
Any number of bits can be stored in a Stream object, limited only by system resources. If the Stream contains more bits
than can be represented by a Long value, Size is truncated and therefore does not accurately represent the length of the
Stream.
Applies To
Stream Object (ADO )
See Also
Size Property (ADO Parameter)
MarshalOptions Property Example (VC++)
11/28/2018 • 4 minutes to read • Edit Online
This example uses the MarshalOptions property to specify what rows are sent back to the server - All Rows or
only Modified Rows.
// BeginMarshalOptionsCpp.cpp
// compile with: /EHsc /c
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <stdio.h>
#include <ole2.h>
#include <conio.h>
#include <malloc.h>
#include "icrsint.h"
BEGIN_ADO_BINDING(CEmployeeRs)
END_ADO_BINDING()
public:
CHAR m_szemp_fname[21];
ULONG lemp_fnameStatus;
CHAR m_szemp_lname[31];
ULONG lemp_lnameStatus;
};
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void MarshalOptionsX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
MarshalOptionsX();
::CoUninitialize();
}
void MarshalOptionsX() {
// Define string variables
char * token1;
_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");
// Define ADO object pointers. Initialize pointers on define. These are in the ADODB:: namespace.
_RecordsetPtr pRstEmployees = NULL;
try {
// Open recordset with names from Employee table.
TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));
pRstEmployees->CursorType = adOpenKeyset;
pRstEmployees->LockType = adLockOptimistic;
pRstEmployees->CursorLocation = adUseClient;
pRstEmployees->Open("SELECT fname, lname FROM Employee ORDER BY lname", strCnn,
adOpenKeyset, adLockOptimistic, adCmdText);
// Change Data in Edit Buffer. Set the final character of the destination string to NULL.
emprs.m_szemp_fname[sizeof(emprs.m_szemp_fname) - 1] = '\0';
// The source string will be truncated if its length is longer than the length of the destination string
minus one.
strncpy_s(emprs.m_szemp_fname, _countof(emprs.m_szemp_fname), "Linda", sizeof(emprs.m_szemp_fname) -1);
// The source string will be truncated if its length is longer than the destination string minus one.
strncpy_s(emprs.m_szemp_lname, _countof(emprs.m_szemp_lname), "Kobara", sizeof(emprs.m_szemp_lname) -1);
if (toupper(opt1)=='Y') {
printf("\nWould you like to send all the rows in the recordset back to the server?\nEnter (y/n):");
char opt2 = _getch();
if (toupper(opt2) == 'Y') {
pRstEmployees->MarshalOptions = adMarshalAll;
picRs->Update(&emprs);
picRs->Update(&emprs);
}
}
else {
printf("\nWould you like to send only modified rows back to the server?\nEnter (y/n):");
char opt3 = _getch();
if (toupper(opt3) == 'Y') {
pRstEmployees->MarshalOptions = adMarshalModifiedOnly;
picRs->Update(&emprs);
}
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for (long i = 0 ; i < nCount ; i++) {
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
MarshalOptions Property (ADO )
ADO Methods
1/25/2019 • 4 minutes to read • Edit Online
BeginTrans, CommitTrans, and RollbackTrans Manages transaction processing within a Connection object
as follows:
CancelUpdate Cancels any changes that were made to the current or new
row of a Recordset object, or the Fields collection of a
Record object, before calling the Update method.
Clear Removes all the Error objects from the Errors collection.
Delete (ADO Fields Collection) Deletes an object from the Fields collection.
Execute (ADO Command) Executes the query, SQL statement, or stored procedure
specified in the CommandText property.
Execute (ADO Connection) Executes the specified query, SQL statement, stored
procedure, or provider-specific text.
Find Searches a Recordset for the row that satisfies the specified
criteria.
GetDataProviderDSO Method Retrieves the underlying OLEDB Data Source object from the
Shape provider.
MoveFirst, MoveLast, MoveNext, and MovePrevious Moves to the first, last, next, or previous record in a specified
Recordset object and makes that record the current record.
NextRecordset Clears the current Recordset object and returns the next
Recordset by advancing through a series of commands.
See Also
ADO API Reference
ADO Collections
ADO Dynamic Properties
ADO Enumerated Constants
Appendix B: ADO Errors
ADO Events
ADO Object Model
ADO Objects and Interfaces
ADO Properties
FetchComplete Event (ADO)
10/1/2018 • 2 minutes to read • Edit Online
The FetchComplete event is called after all the records in a lengthy asynchronous operation have been retrieved
into the Recordset.
Syntax
FetchComplete pError, adStatus, pRecordset
Parameters
pError
An Error object. It describes the error that occurred if the value of adStatus is adStatusErrorsOccurred;
otherwise it is not set.
adStatus
An EventStatusEnum status value. When this event is called, this parameter is set to adStatusOK if the operation
that caused the event was successfull, or to adStatusErrorsOccurred if the operation failed.
Before this event returns, set this parameter to adStatusUnwantedEvent to prevent subsequent notifications.
pRecordset
A Recordset object. The object for which the records were retrieved.
Remarks
To use FetchComplete with Microsoft Visual Basic, Visual Basic 6.0 or later is required.
See Also
ADO Events Model Example (VC++)
ADO Event Handler Summary
CacheSize Property Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the CacheSize property to show the difference in performance for an operation performed with
and without a 30-record cache.
'BeginCacheSizeVB
For intLoop = 1 To 2
rstRoySched.MoveFirst
sngEnd = Timer
sngNoCache = sngEnd - sngStart
sngEnd = Timer
sngCache = sngEnd - sngStart
' clean up
rstRoySched.Close
Set rstRoySched = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstRoySched Is Nothing Then
If rstRoySched.State = adStateOpen Then rstRoySched.Close
End If
Set rstRoySched = Nothing
See Also
CacheSize Property (ADO )
Recordset Object (ADO )
Error (ADO - WFC Syntax)
10/1/2018 • 2 minutes to read • Edit Online
package com.ms.wfc.data
Properties
See Also
Error Object
EditMode Property
10/1/2018 • 2 minutes to read • Edit Online
Return Value
Returns an EditModeEnum value.
Remarks
ADO maintains an editing buffer associated with the current record. This property indicates whether changes
have been made to this buffer, or whether a new record has been created. Use the EditMode property to
determine the editing status of the current record. You can test for pending changes if an editing process has
been interrupted and determine whether you need to use the Update or CancelUpdate method.
In immediate update mode the EditMode property is reset to adEditNone after a successful call to the
Update method is called. When a call to Delete does not successfully delete the record or records in the data
source (for example, because of referential integrity violations), the Recordset remains in edit mode (EditMode
= adEditInProgress). Therefore, CancelUpdate must be called before moving off the current record (for
example with Move, NextRecordset, or Close ).
In batch update mode (in which the provider caches multiple changes and writes them to the underlying data
source only when you call the UpdateBatch method), the value of the EditMode property is changed when the
first operation is performed and it is not reset by a call to the Update method. Subsequent operations do not
change the value of the EditMode property, even if different operations are performed. For example, if the first
operation is to add a new record, and the second makes changes to an existing record, the property of
EditMode will still be adEditAdd. The EditMode property is not reset to adEditNone until after the call to
UpdateBatch. To determine what operations have been performed, set the Filter property to adFilterPending so
that only records with pending changes will be visible and examine the Status property of each record to
determine what changes have been made to the data.
NOTE
EditMode can return a valid value only if there is a current record. EditMode will return an error if BOF or EOF is true, or if
the current record has been deleted.
Applies To
Recordset Object (ADO )
See Also
CursorType, LockType, and EditMode Properties Example (VB )
CursorType, LockType, and EditMode Properties Example (VC++)
AddNew Method (ADO )
Delete Method (ADO Recordset)
CancelUpdate Method (ADO )
Update Method
Error Object
10/1/2018 • 2 minutes to read • Edit Online
Contains details about data access errors that pertain to a single operation involving the provider.
Remarks
Any operation involving ADO objects can generate one or more provider errors. As each error occurs, one
or more Error objects are placed in the Errors collection of the Connection object. When another ADO
operation generates an error, the Errors collection is cleared, and the new set of Error objects is placed in
the Errors collection.
NOTE
Each Error object represents a specific provider error, not an ADO error. ADO errors are exposed to the run-time
exception-handling mechanism. For example, in Microsoft Visual Basic, the occurrence of an ADO-specific error will
trigger an On Error event and appear in the Error object. For a complete list of ADO errors, see the ErrorValueEnum
topic.
You can read an Error object's properties to obtain specific details about each error, including the following:
The Description property, which contains the text of the error. This is the default property.
The Number property, which contains the Long integer value of the error constant.
The Source property, which identifies the object that raised the error. This is particularly useful when
you have several Error objects in the Errors collection following a request to a data source.
The SQLState and NativeError properties, which provide information from SQL data sources.
When a provider error occurs, it is placed in the Errors collection of the Connection object. ADO supports
the return of multiple errors by a single ADO operation to allow for error information specific to the
provider. To obtain this rich error information in an error handler, use the appropriate error-trapping
features of the language or environment you are working with, then use nested loops to enumerate the
properties of each Error object in the Errors collection.
NOTE
Microsoft Visual Basic and VBScript Users If there is no valid Connection object, you will need to retrieve error
information from the Error object.
Just as providers do, ADO clears the OLE Error Info object before making a call that could potentially
generate a new provider error. However, the Errors collection on the Connection object is cleared and
populated only when the provider generates a new error, or when the Clear method is called.
Some properties and methods return warnings that appear as Error objects in the Errors collection but do
not halt a program's execution. Before you call the Resync, UpdateBatch, or CancelBatch methods on a
Recordset object; the Open method on a Connection object; or set the Filter property on a Recordset
object, call the Clear method on the Errors collection. That way, you can read the Count property of the
Errors collection to test for returned warnings.
The Error object is not safe for scripting.
This section contains the following topic.
Error Object Properties, Methods, and Events
See Also
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VB )
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example
(VC++)
Connection Object (ADO )
Errors Collection (ADO )
Appendix A: Providers
ADO - WFC Syntax Index
10/1/2018 • 2 minutes to read • Edit Online
The ADO Language Reference uses the Microsoft Visual Basic programming language to illustrate ADO method
and property syntax. This index is a cross-reference to the ADO Language Reference topics, based on ADO for
Windows Foundation Classes (ADO/WFC ). When differences in syntax arise, use the function signatures in this
index, as opposed to the syntax listings in the language reference topic.
Method and property syntax are listed for the following elements:
See Also
Handling ADO Events
Microsoft ActiveX Data Objects (ADO )
Source Property (ADO Recordset)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the Source property to specify a data source for a Recordset object using one of the following: a
Command object variable, an SQL statement, a stored procedure, or a table name.
If you set the Source property to a Command object, the ActiveConnection property of the Recordset object
will inherit the value of the ActiveConnection property for the specified Command object. However, reading
the Source property does not return a Command object; instead, it returns the CommandText property of the
Command object to which you set the Source property.
If the Source property is an SQL statement, a stored procedure, or a table name, you can optimize performance
by passing the appropriate Options argument with the Open method call.
The Source property is read/write for closed Recordset objects and read-only for open Recordset objects.
Applies To
Recordset Object (ADO )
See Also
Source Property Example (VB )
Source Property (ADO Error)
Source Property (ADO Record)
Command Object (ADO)
10/1/2018 • 3 minutes to read • Edit Online
Defines a specific command that you intend to execute against a data source.
Remarks
Use a Command object to query a database and return records in a Recordset object, to execute a
bulk operation, or to manipulate the structure of a database. Depending on the functionality of the
provider, some Command collections, methods, or properties may generate an error when they
are referenced.
With the collections, methods, and properties of a Command object, you can do the following:
Define the executable text of the command (for example, an SQL statement) with the
CommandText property. Alternatively, for command or query structures other than simple
strings (for example, XML template queries) define the command with the CommandStream
property.
Optionally, indicate the command dialect used in the CommandText or CommandStream
with the Dialect property.
Define parameterized queries or stored-procedure arguments with Parameter objects and
the Parameters collection.
Indicate whether parameter names should be passed to the provider with the
NamedParameters property.
Execute a command and return a Recordset object if appropriate with the Execute method.
Specify the type of command with the CommandType property prior to execution to
optimize performance.
Control whether the provider saves a prepared (or compiled) version of the command prior
to execution with the Prepared property.
Set the number of seconds that a provider will wait for a command to execute with the
CommandTimeout property.
Associate an open connection with a Command object by setting its ActiveConnection
property.
Set the Name property to identify the Command object as a method on the associated
Connection object.
Pass a Command object to the Source property of a Recordset to obtain data.
Access provider-specific attributes with the Properties collection.
NOTE
To execute a query without using a Command object, pass a query string to the Execute method of a
Connection object or to the Open method of a Recordset object. However, a Command object is
required when you want to persist the command text and re-execute it, or use query parameters.
To create a Command object independently of a previously defined Connection object, set its
ActiveConnection property to a valid connection string. ADO still creates a Connection object,
but it does not assign that object to an object variable. However, if you are associating multiple
Command objects with the same connection, you should explicitly create and open a Connection
object; this assigns the Connection object to an object variable. Make sure that the Connection
object was opened successfully before you assign it to the ActiveConnection property of the
Command object, because assigning a closed Connection object causes an error. If you do not set
the ActiveConnection property of the Command object to this object variable, ADO creates a
new Connection object for each Command object, even if you use the same connection string.
To execute a Command, call it by its Name property on the associated Connection object. The
Command must have its ActiveConnection property set to the Connection object. If the
Command has parameters, pass their values as arguments to the method.
If two or more Command objects are executed on the same connection and either Command
object is a stored procedure with output parameters, an error occurs. To execute each Command
object, use separate connections or disconnect all other Command objects from the connection.
The Parameters collection is the default member of the Command object. As a result, the
following two code statements are equivalent.
objCmd.Parameters.Item(0)
objCmd(0)
See Also
Connection Object (ADO )
Parameters Collection (ADO )
Properties Collection (ADO )
Appendix A: Providers
GetRows Method Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the GetRows method to retrieve a specified number of rows from a Recordset and to fill an
array with the resulting data. The GetRows method will return fewer than the desired number of rows in two
cases: either if EOF has been reached, or if GetRows tried to retrieve a record that was deleted by another user.
The function returns False only if the second case occurs. The GetRowsOK function is required for this procedure
to run.
'BeginGetRowsVB
For x = 0 To intRows - 1
For y = 0 To 2
Debug.Print arrEmployees(y, x) & " ";
Next y
Debug.Print vbCrLf
Next x
' clean up
rstEmployees.Close
Cnxn.Close
Set rstEmployees = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstEmployees Is Nothing Then
If rstEmployees.State = adStateOpen Then rstEmployees.Close
End If
Set rstEmployees = Nothing
See Also
GetRows Method (ADO )
Recordset Object (ADO )
State Property Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the State property to display a message while asynchronous connections are opening and
asynchronous commands are executing.
'BeginStateVB
cmdRestore.Execute , , adAsyncExecute
Do Until cmdRestore.State <> adStateExecuting
Debug.Print "Restore command executing...."
Loop
' clean up
Cnxn1.Close
Cnxn2.Close
Set Cnxn1 = Nothing
Set Cnxn2 = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not Cnxn1 Is Nothing Then
If Cnxn1.State = adStateOpen Then Cnxn1.Close
End If
Set Cnxn1 = Nothing
See Also
Recordset Object (ADO )
State Property (ADO )
RowPosition Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Gets or sets an OLE DB RowPosition object from/on an ADORecordsetConstruction object. When you use
put_RowPosition to set the RowPosition object, the resulting Recordset object uses the RowPosition object to
determine the current row.
Read/write.
Syntax
HRESULT get_RowPosition([out, retval] IUnknown** ppRowPos);
HRESULT put_RowPosition([in] IUnknown* pRowPos);
Parameters
ppRowPos
Pointer to an OLE DB RowPosition object.
PRowPos
An OLE DB RowPosition object.
Return Values
This property method returns the standard HRESULT values, including S_OK and E_FAIL.
Remarks
When this property is set, if the Rowset object on the RowPosition object is different from the Rowset object on
the Recordset object, the former overrides the latter. The same behavior applies to the current Chapter of the
RowPosition as well.
Applies To
ADORecordsetConstruction Interface
AddNew Method Example (VC++)
10/1/2018 • 3 minutes to read • Edit Online
This example uses the AddNew method to create a new record with the specified name.
// BeginAddNewCpp.cpp
// compile with: /EHsc /c
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include "conio.h"
#include "icrsint.h"
END_ADO_BINDING()
public:
CHAR m_sz_empid[10];
ULONG lemp_empidStatus;
CHAR m_sz_fname[40];
ULONG lemp_fnameStatus;
CHAR m_sz_lname[41];
ULONG lemp_lnameStatus;
};
// Function declaration
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void AddNewX();
void PrintProviderError(_ConnectionPtr pConnection);
if (pstrRet == NULL)
return 0;
if (!strrchr(strDest, '\n'))
// Exhaust the input buffer.
do {
fgets(strExBuff, sizeof(strExBuff), stdin);
} while (!strrchr(strExBuff, '\n'));
else
// Replace '\n' with '\0'
strDest[strrchr(strDest, '\n') - strDest] = '\0';
return strlen(strDest);
}
int main() {
HRESULT hr = S_OK;
if (FAILED(::CoInitialize(NULL)))
return -1;
if (SUCCEEDED(hr)) {
AddNewX();
::CoUninitialize();
}
}
void AddNewX() {
// Define ADO object pointers. Initialize pointers on define.
_RecordsetPtr pRstEmployees = NULL;
_ConnectionPtr pConnection = NULL;
HRESULT hr = S_OK;
try {
// Open a connection
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open(strCnn, "", "", adConnectUnspecified);
// You have to explicitly pass the Cursor type and LockType to the Recordset here
pRstEmployees->Open("employee", _variant_t((IDispatch *) pConnection, true),
adOpenKeyset, adLockOptimistic, adCmdTable);
// Get data from the user.The employee id must be formatted as first,middle and last
// initial, five numbers,then M or F to signify the gender. For example, the
// employee id for Bill A. Sorensen would be "BAS55555M".
printf("Enter Employee Id: ");
myscanf(emprs.m_sz_empid, sizeof(emprs.m_sz_empid));
strId = emprs.m_sz_empid;
printf("Enter First Name: ");
myscanf(emprs.m_sz_fname, sizeof(emprs.m_sz_fname));
printf("Enter Last Name:");
myscanf(emprs.m_sz_lname, sizeof(emprs.m_sz_lname));
// Proceed if user entered id, the first and the last name.
if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}
if ( (pConnection->Errors->Count) > 0) {
nCount = pConnection->Errors->Count;
See Also
AddNew Method (ADO )
Recordset Object (ADO )
NumericScale and Precision Properties Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the NumericScale and Precision properties to display the numeric scale and precision of fields
in the Discounts table of the Pubs database.
'BeginNumericScaleVB
Cnxn.Open strCnxn
' clean up
rstDiscounts.Close
Cnxn.Close
Set rstDiscounts = Nothing
Set Cnxn = Nothing
End Sub
'EndNumericScaleVB
See Also
Field Object
NumericScale Property (ADO )
Parameter Object
Precision Property (ADO )
Stream Object Properties, Methods, and Events
10/1/2018 • 2 minutes to read • Edit Online
Properties
Charset Property
EOS Property
LineSeparator Property
Mode Property
Position Property
Size Property (ADO Stream)
State Property
Type Property (ADO Stream)
Methods
Cancel Method
Close Method
CopyTo Method
Flush Method
LoadFromFile Method
Open Method (ADO Stream)
Read Method
ReadText Method
SaveToFile Method
SetEOS Method
SkipLine Method
Stat Method
Write Method
WriteText Method
Events
None.
See Also
Stream Object (ADO )
Stat Method
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Long stream.Stat(StatStg, StatFlag)
Return Value
A Long value indicating the status of the operation.
Parameters
StatStg
A STATSTG structure that will be filled in with information about the stream. The implementation of the Stat
method used by the ADO Stream object does not fill in all of the fields of the structure.
StatFlag
Specifies that this method does not return some of the members in the STATSTG structure, thus saving a memory
allocation operation. Values are taken from the STATFLAG enumeration. The STATFLAG enumeration has two
values
CONSTANT VALUE
STATFLAG_DEFAULT 0
STATFLAG_NONAME 1
Remarks
The version of the Stat method implemented for the ADO Stream object fills in the following fields of the STATSTG
structure:
pwcsName
A string containing the name of the stream, if one is available and the StatFlag value STATFLAG_NONAME was
not specified.
cbSize
Specifies the size in bytes of the stream or byte array.
mtime
Indicates the last modification time for this storage, stream, or byte array.
ctime
Indicates the creation time for this storage, stream, or byte array.
atime
Indicates the last access time for this storage, stream or byte array.
If STATFLAG_NONAME is specified in the StatFlag parameter, the name of the stream is not returned.
If STATFLAG_NONAME was not specified in the StatFlag parameter, and there is no name available for the current
stream, this value will be E_NOTIMPL.
Applies To
Stream Object (ADO )
LockType Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Set the LockType property before opening a Recordset to specify what type of locking the provider should use
when opening it. Read the property to return the type of locking in use on an open Recordset object.
Providers may not support all lock types. If a provider cannot support the requested LockType setting, it will
substitute another type of locking. To determine the actual locking functionality available in a Recordset object,
use the Supports method with adUpdate and adUpdateBatch.
The adLockPessimistic setting is not supported if the CursorLocation property is set to adUseClient. If an
unsupported value is set, then no error will result; the closest supported LockType will be used instead.
The LockType property is read/write when the Recordset is closed and read-only when it is open.
NOTE
Remote Data Service Usage When used on a client-side Recordset object, the LockType property can only be set to
adLockBatchOptimistic.
Applies To
Recordset Object (ADO )
See Also
CursorType, LockType, and EditMode Properties Example (VB )
CursorType, LockType, and EditMode Properties Example (VC++)
CancelBatch Method (ADO )
UpdateBatch Method
PropertyAttributesEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.PropertyAttributes.NOTSUPPORTED
AdoEnums.PropertyAttributes.REQUIRED
AdoEnums.PropertyAttributes.OPTIONAL
AdoEnums.PropertyAttributes.READ
AdoEnums.PropertyAttributes.WRITE
Applies To
Attributes Property (ADO )
CreateParameter Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Set parameter = command.CreateParameter (Name, Type, Direction, Size, Value)
Return Value
Returns a Parameter object.
Parameters
Name
Optional. A String value that contains the name of the Parameter object.
Type
Optional. A DataTypeEnum value that specifies the data type of the Parameter object.
Direction
Optional. A ParameterDirectionEnum value that specifies the type of Parameter object.
Size
Optional. A Long value that specifies the maximum length for the parameter value in characters or bytes.
Value
Optional. A Variant that specifies the value for the Parameter object.
Remarks
Use the CreateParameter method to create a new Parameter object with a specified name, type, direction,
size, and value. Any values you pass in the arguments are written to the corresponding Parameter properties.
This method does not automatically append the Parameter object to the Parameters collection of a Command
object. This lets you set additional properties whose values ADO will validate when you append the Parameter
object to the collection.
If you specify a variable-length data type in the Type argument, you must either pass a Size argument or set the
Size property of the Parameter object before appending it to the Parameters collection; otherwise, an error
occurs.
If you specify a numeric data type (adNumeric or adDecimal) in the Type argument, then you must also set
the NumericScale and Precision properties.
Applies To
Command Object (ADO )
See Also
Append and CreateParameter Methods Example (VB )
Append and CreateParameter Methods Example (VC++)
Append Method (ADO )
Parameter Object
Parameters Collection (ADO )
DataSpace (ADO - WFC Syntax)
10/1/2018 • 2 minutes to read • Edit Online
The createObject method of the DataSpace class specifies both a business object to process client application
requests (progid) and the communications protocol and server ( connection). createObject returns an ObjectProxy
object that represents the server.
package com.ms.wfc.data
Constructor
public DataSpace()
Methods
Properties
See Also
DataSpace Object (RDS )
ErrorValueEnum
11/28/2018 • 4 minutes to read • Edit Online
NOTE
OLE DB errors may be passed to your ADO application. Typically, these can be identified by a Windows facility code of 4. For
example, 0x8004.
adErrCantChangeProvider 3220 -2146825068 0X800A0C94 Supplied provider differs from the one
already being used.
adErrColumnNotOnThisRow 3726 -2146824562 0x800A0E8E Record does not contain this field.
CONSTANT VALUE DESCRIPTION
adErrIntegrityViolation 3719 -2146824569 0x800A0E87 Data value conflicts with the integrity
constraints of the field.
adErrInvalidArgument 3001 -2146825287 0x800A0BB9 Arguments are of the wrong type, are
out of acceptable range, or are in
conflict with one another.
adErrProviderFailed 3000 -2146825288 0x800A0BB8 Provider did not perform the requested
operation.
adErrSchemaViolation 3722 -2146824566 0x800A0E8A Data value conflicts with the data type
or constraints of the field.
adErrUnavailable 3736 -2146824552 0x800A0E98 Operation did not complete and the
status is unavailable. The field may be
unavailable or the operation was not
attempted.
adErrURLDoesNotExist 3727 -2146824561 0x800A0E8F Either the source URL or the parent of
the destination URL does not exist.
adErrURLNamedRowDoesNotExist 3737 -2146824551 0x800A0E99 Record named by this URL does not
exist.
adWrnSecurityDialog 3717 -2146824571 0x800A0E85 For internal use only. Do not use.
adWrnSecurityDialogHeader 3718 -2146824570 0x800A0E86 For internal use only. Do not use.
ADO/WFC Equivalent
Package: com.ms.wfc.data
Only the following subsets of ADO/WFC equivalents are defined.
CONSTANT
AdoEnums.ErrorValue.BOUNDTOCOMMAND
AdoEnums.ErrorValue.DATACONVERSION
AdoEnums.ErrorValue.FEATURENOTAVAILABLE
AdoEnums.ErrorValue.ILLEGALOPERATION
AdoEnums.ErrorValue.INTRANSACTION
AdoEnums.ErrorValue.INVALIDARGUMENT
AdoEnums.ErrorValue.INVALIDCONNECTION
AdoEnums.ErrorValue.INVALIDPARAMINFO
AdoEnums.ErrorValue.ITEMNOTFOUND
AdoEnums.ErrorValue.NOCURRENTRECORD
AdoEnums.ErrorValue.NOTEXECUTING
AdoEnums.ErrorValue.NOTREENTRANT
AdoEnums.ErrorValue.OBJECTCLOSED
AdoEnums.ErrorValue.OBJECTINCOLLECTION
AdoEnums.ErrorValue.OBJECTNOTSET
AdoEnums.ErrorValue.OBJECTOPEN
AdoEnums.ErrorValue.OPERATIONCANCELLED
AdoEnums.ErrorValue.PROVIDERNOTFOUND
AdoEnums.ErrorValue.STILLCONNECTING
AdoEnums.ErrorValue.STILLEXECUTING
AdoEnums.ErrorValue.UNSAFEOPERATION
Applies To
Number Property (ADO )
See Also
ADO Error Codes
Flush Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Forces the contents of the Stream remaining in the ADO buffer to the underlying object with which the Stream is
associated.
Syntax
Stream.Flush
Remarks
This method can be used to send the contents of the stream buffer to the underlying object: for example, the node
or file represented by the URL that is the source of the Stream object. This method should be called when you
want to ensure that all changes that were made to the contents of a Stream have been written. However, with
ADO it is not usually necessary to call Flush, as ADO continuously flushes its buffer as much as possible in the
background. Changes to the content of a Stream are made automatically, not cached until Flush is called.
Closing a Stream with the Close method flushes the contents of a Stream automatically; there is no need to
explicitly call Flush immediately before Close.
Applies To
Stream Object (ADO )
ADOStreamConstruction Interface
10/1/2018 • 2 minutes to read • Edit Online
The ADOStreamConstruction interface is used to construct an ADO Stream object from an OLE DB IStream
object in a C/C++ application.
Properties
Methods
None.
Events
None.
Remarks
Given an OLE DB IStream object ( pStream ), the construction of an ADO Stream object ( adoStr ) amounts to the
following three basic operations:
1. Create an ADO Stream object:
Stream20Ptr adoStr;
adoStr.CreateInstance(__uuidof(Stream));
adoStreamConstructionPtr adoStrConstruct=NULL;
adoStr->QueryInterface(__uuidof(ADOStreamConstruction),
(void**)&adoStrConstruct);
Call the IADOStreamConstruction::get_Stream property method to set the OLE DB IStream object on the ADO
Stream object:
IUnknown *pUnk=NULL;
pRowset->QueryInterface(IID_IUnknown, (void**)&pUnk);
adoStrConstruct->put_Stream(pUnk);
The resultant adoStr object now represents the ADO Stream object constructed from the OLE DB IStream
object.
Requirements
Version: ADO 2.0 or a later version
Library: msado15.dll
UUID: 00000283-0000-0010-8000-00AA006D2EA4
See Also
ADO API Reference
IsolationLevel and Mode Properties Example (VC++)
10/1/2018 • 3 minutes to read • Edit Online
This example uses the Mode property to open an exclusive connection, and the IsolationLevel property to open a
transaction that is conducted in isolation of other transactions.
Example
// BeginIsolationLevelCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF","EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
#include "icrsint.h"
public:
CHAR m_szau_Title[81];
ULONG lau_TitleStatus;
CHAR m_szau_Type[13];
ULONG lau_TypeStatus;
};
// Function Declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void IsolationLevelX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
IsolationLevelX();
::CoUninitialize();
}
void IsolationLevelX() {
// Define ADO ObjectPointers. Initialize Pointers on define. These are in the ADODB :: namespace.
_RecordsetPtr pRstTitles = NULL;
_ConnectionPtr pConnection = NULL;
try {
// Open Connection and Titles Table
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Mode = adModeShareExclusive;
pConnection->IsolationLevel = adXactIsolated;
pConnection->Open(strCnn,"", "", adConnectUnspecified);
TESTHR(pRstTitles.CreateInstance(__uuidof(Recordset)));
pRstTitles->CursorType = adOpenDynamic;
pRstTitles->LockType = adLockPessimistic;
pConnection->BeginTrans();
// Open an IADORecordBinding interface pointer which we will use for binding Recordset to a class.
TESTHR(pRstTitles->QueryInterface( __uuidof(IADORecordBinding), (LPVOID*)&picRs));
while (!(pRstTitles->EndOfFile)) {
// Set the final character of the destination string to NULL.
p_TempStr[sizeof(titlers.m_szau_Type) - 1] = '\0';
// Copy "self_help" title field. The source string will get truncated if its length is
// longer than the length of the destination string minus one.
strncpy_s(titlers.m_szau_Type, sizeof(titlers.m_szau_Type), "self_help",
sizeof(titlers.m_szau_Type) - 1);
picRs->Update(&titlers);
}
pRstTitles->MoveNext();
}
while (!pRstTitles->EndOfFile) {
printf("%s - %s\n",titlers.lau_TitleStatus == adFldOK ?
titlers.m_szau_Title :"<NULL>",
titlers.lau_TypeStatus == adFldOK ?
titlers.m_szau_Type :"<NULL>");
pRstTitles->MoveNext();
}
}
catch(_com_error &e) {
// Notify the user of errors if any.
PrintProviderError(pConnection);
PrintComError(e);
}
if (pRstTitles)
if (pRstTitles->State == adStateOpen)
pRstTitles->Close();
if (pConnection)
if (pConnection->State == adStateOpen) {
// Restore Original Data
pConnection->RollbackTrans();
pConnection->Close();
}
if ((pConnection->Errors->Count)>0) {
long nCount = pConnection->Errors->Count;
See Also
IsolationLevel Property
Mode Property (ADO )
GetString Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Variant = recordset.GetString(StringFormat, NumRows, ColumnDelimiter, RowDelimiter, NullExpr)
Return Value
Returns the Recordset as a string-valued Variant (BSTR ).
Parameters
StringFormat
A StringFormatEnum value that specifies how the Recordset should be converted to a string. The RowDelimiter,
ColumnDelimiter, and NullExpr parameters are used only with a StringFormat of adClipString.
NumRows
Optional. The number of rows to be converted in the Recordset. If NumRows is not specified, or if it is greater
than the total number of rows in the Recordset, then all the rows in the Recordset are converted.
ColumnDelimiter
Optional. A delimiter used between columns, if specified, otherwise the TAB character.
RowDelimiter
Optional. A delimiter used between rows, if specified, otherwise the CARRIAGE RETURN character.
NullExpr
Optional. An expression used in place of a null value, if specified, otherwise the empty string.
Remarks
Row data, but no schema data, is saved to the string. Therefore, a Recordset cannot be reopened using this string.
This method is equivalent to the RDO GetClipString method.
Applies To
Recordset Object (ADO )
See Also
GetString Method Example (VB )
MoveFirst, MoveLast, MoveNext, and MovePrevious
Methods Example (VBScript)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the MoveFirst, MoveLast, MoveNext, and MovePrevious methods to move the record pointer of
a Recordset based on the supplied command.
Cut and paste the following code into Notepad or another text editor, and save it as MoveFirstVBS.asp. You can
view the result in any browser.
<SCRIPT LANGUAGE="VBScript">
<!--
Sub cmdDown_OnClick
'Set Values in Form Input Boxes and Submit Form
Document.form.MoveAction.Value = "MovePrev"
Document.Form.Submit
End Sub
Sub cmdUp_OnClick
Document.form.MoveAction.Value = "MoveNext"
Document.Form.Submit
End Sub
Sub cmdFirst_OnClick
Document.form.MoveAction.Value = "MoveFirst"
Document.Form.Submit
End Sub
Sub cmdLast_OnClick
Document.form.MoveAction.Value = "MoveLast"
Document.Form.Submit
End Sub
//-->
</SCRIPT>
</HEAD>
<body bgcolor="white">
<h1 align="center">ADO MoveNext, MovePrevious <br> MoveLast & MoveFirst Methods</h1>
<% ' to integrate/test this code replace the
' Data Source value in the Connection string%>
<%
' connection and recordset variables
Dim Cnxn, strCnxn
Dim rsEmployees, strSQLEmployees
rsEmployees.ActiveConnection = Cnxn
rsEmployees.CursorLocation = adUseClient
rsEmployees.CursorType = adOpenKeyset
rsEmployees.LockType = adLockOptimistic
rsEmployees.Source = strSQLEmployees
rsEmployees.Open
rsEmployees.MoveFirst
rsEmployees.AbsolutePosition = varPosition
Case "MoveNext"
rsEmployees.MoveNext
If rsEmployees.EOF Then
rsEmployees.MoveLast
strMessage = "Can't move beyond the last record."
End If
Case "MovePrev"
rsEmployees.MovePrevious
If rsEmployees.BOF Then
rsEmployees.MoveFirst
strMessage = "Can't move beyond the first record."
End If
Case "MoveLast"
rsEmployees.MoveLast
Case "MoveFirst"
rsEmployees.MoveFirst
End Select
End If
%>
<hr>
<!-- Use Hidden Form Fields to record values to send to Server -->
<HR>
</BODY>
<%
' clean up
If rsEmployees.State = adStateOpen then
rsEmployees.Close
End If
If Cnxn.State = adStateOpen then
Cnxn.Close
End If
%>
</HTML>
<!-- EndMoveFirstVBS -->
See Also
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods (ADO )
Recordset Object (ADO )
Field (Visual C++ Syntax Index with #import)
10/1/2018 • 2 minutes to read • Edit Online
Methods
HRESULT AppendChunk( const _variant_t & Data );
Properties
long GetActualSize( );
__declspec(property(get=GetActualSize)) long ActualSize;
long GetAttributes( );
void PutAttributes( long pl );
__declspec(property(get=GetAttributes,put=PutAttributes)) long Attributes;
IUnknownPtr GetDataFormat( );
void PutRefDataFormat( IUnknown * ppiDF );
__declspec(property(get=GetDataFormat,put=PutRefDataFormat)) IunknownPtr
DataFormat;
long GetDefinedSize( );
void PutDefinedSize( long pl );
__declspec(property(get=GetDefinedSize,put=PutDefinedSize)) long
DefinedSize;
_bstr_t GetName( );
__declspec(property(get=GetName)) _bstr_t Name;
_variant_t GetOriginalValue( );
__declspec(property(get=GetOriginalValue)) _variant_t OriginalValue;
_variant_t GetUnderlyingValue( );
__declspec(property(get=GetUnderlyingValue)) _variant_t UnderlyingValue;
_variant_t GetValue( );
void PutValue( const _variant_t & pvar );
__declspec(property(get=GetValue,put=PutValue)) _variant_t Value;
See Also
Field Object
RecordOpenOptionsEnum
10/1/2018 • 2 minutes to read • Edit Online
Specifies options for opening a Record. These values may be combined by using OR.
ADO/WFC Equivalent
These constants do not have ADO/WFC equivalents.
Applies To
Open Method (ADO Record)
IsolationLevelEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.IsolationLevel.UNSPECIFIED
AdoEnums.IsolationLevel.CHAOS
AdoEnums.IsolationLevel.BROWSE
CONSTANT
AdoEnums.IsolationLevel.READUNCOMMITTED
AdoEnums.IsolationLevel.CURSORSTABILITY
AdoEnums.IsolationLevel.READCOMMITTED
AdoEnums.IsolationLevel.REPEATABLEREAD
AdoEnums.IsolationLevel.ISOLATED
AdoEnums.IsolationLevel.SERIALIZABLE
Applies To
IsolationLevel Property
Connection (ADO - WFC Syntax)
10/1/2018 • 2 minutes to read • Edit Online
package com.ms.wfc.data
Constructor
public Connection()
public Connection(String connectionstring)
Methods
The executeUpdate method is a special case method that calls the underlying ADO execute method with certain
parameters. The executeUpdate method does not support the return of a Recordset object, so the execute
method's options parameter is modified with AdoEnums.ExecuteOptions.NORECORDS. After the execute
method completes, its updated RecordsAffected parameter is passed back to the executeUpdate method, which is
finally returned as an int.
Properties
public int getAttributes()
public void setAttributes(int attr)
public int getCommandTimeout()
public void setCommandTimeout(int timeout)
public String getConnectionString()
public void setConnectionString(String con)
public int getConnectionTimeout()
public void setConnectionTimeout(int timeout)
public int getCursorLocation()
public void setCursorLocation(int cursorLoc)
public String getDefaultDatabase()
public void setDefaultDatabase(String db)
public int getIsolationLevel()
public void setIsolationLevel(int level)
public int getMode()
public void setMode(int mode)
public String getProvider()
public void setProvider(String provider)
public int getState()
public String getVersion()
public AdoProperties getProperties()
public com.ms.wfc.data.Errors getErrors()
Events
For more information about ADO/WFC events, see ADO Event Instantiation by Language.
See Also
Connection Object (ADO )
Status Property (ADO Field)
10/1/2018 • 2 minutes to read • Edit Online
Return Value
Returns a FieldStatusEnum value. The default value is adFieldOK.
Remarks
Record Field Status
Changes to the value of a Field object in the Fields collection of a Record object are cached until the object's
Update method is called. At that point, if the change to the Field's value caused an error, OLE DB raises the error
DB_E_ERRORSOCCURRED (2147749409). The Status property of any of the Field objects in the Fields
collection that caused the error will contain a value from the FieldStatusEnum describing the cause of the
problem.
To enhance performance, additions and deletions to the Fields collections of the Record object are cached until
the Update method is called, and then the changes are made in a batch optimistic update. If the Update method
is not called, the server is not updated. If any updates fail then an OLE DB provider error
(DB_E_ERRORSOCCURRED ) is returned and the Status property indicates the combined values of the operation
and error status code. For example, adFieldPendingInsert OR adFieldPermissionDenied. The Status
property for each Field can be used to determine why the Field was not added, modified, or deleted.
Many types of problems encountered when adding, modifying, or deleting a Field are reported through the
Status property. For example, if the user deletes a Field, it is marked for deletion from the Fields collection. If the
subsequent Update returns an error because the user tried to delete a Field for which they do not have
permission, the Field will have a Status of adFieldPermissionDenied OR adFieldPendingDelete. Calling the
CancelUpdate method restores original values and sets the Status to adFieldOK.
Similarly, the Update method may return an error because a new Field was added and given an inappropriate
value. In that case the new Field will be in the Fields collection and have a status of adFieldPendingInsert and
perhaps adFieldCantCreate (depending upon your provider). You can supply an appropriate value for the new
Field and call Update again.
Applies To
Field Object
See Also
Status Property Example (Field) (VB )
Status Property Example (VC++)
Fields Collection Properties, Methods, and Events
10/1/2018 • 2 minutes to read • Edit Online
Properties
Count Property
Item Property
Methods
Append Method
CancelUpdate Method
Delete Method (ADO Fields Collection)
Refresh Method
Resync Method
Update Method
Events
None.
See Also
Fields Collection (ADO )
NextRecordset Method Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the NextRecordset method to view the data in a recordset that uses a compound command
statement made up of three separate SELECT statements.
// BeginNextRecordsetCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <stdio.h>
#include <ole2.h>
#include <conio.h>
#include <stdlib.h>
//Function Declaration.
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void NextRecordsetX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
NextRecordsetX();
::CoUninitialize();
}
void NextRecordsetX() {
// Define ADO object pointers. Initialize pointers on define. These are in the ADODB:: namespace.
_RecordsetPtr pRstCompound = NULL;
try {
// Open recordset from Authors table.
TESTHR(pRstCompound.CreateInstance(__uuidof(Recordset)));
while (!pRstCompound->EndOfFile) {
index.iVal = 0;
printf("%s\t", (LPCSTR)(_bstr_t)pRstCompound->GetFields()->GetItem(& index)->Value);
index.iVal = 1;
printf("%s\n", (LPCSTR)(_bstr_t)pRstCompound->Fields->GetItem(& index)->Value);
pRstCompound->MoveNext();
}
long lngRec = 0;
pRstCompound = pRstCompound->NextRecordset((VARIANT *)lngRec);
intCount = intCount + 1;
}
}
catch(_com_error &e) {
// Notify the user of errors if any. Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstCompound->GetActiveConnection();
// GetActiveConnection returns connect string if connection is not open, else returns Connection object.
switch(vtConnect.vt) {
case VT_BSTR:
PrintComError(e);
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
NextRecordset Method (ADO )
Chapter Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Gets or sets an OLE DB Chapter object from/on an ADORecordsetConstruction Interface object. When you use
put_Chapter to set the Chapter object, a subset of rows is turned into an ADO Recordset Object object. This sets
the current chapter of the Rowsetobject. This property is read/write.
Syntax
HRESULT get_Chapter([out, retval] long* plChapter);
HRESULT put_Chapter([in] long lChapter);
Parameters
plChapter
Pointer to the handle of a chapter.
LChapter
Handle of a chapter.
Return Values
This property method returns the standard HRESULT values, including S_OK and E_FAIL.
Applies To
ADORecordsetConstruction Interface
SaveToFile Method
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Stream.SaveToFile FileName, SaveOptions
Parameters
FileName
A String value that contains the fully-qualified name of the file to which the contents of the Stream will be saved.
You can save to any valid local location, or any location you have access to via a UNC value.
SaveOptions
A SaveOptionsEnum value that specifies whether a new file should be created by SaveToFile, if it does not
already exist. Default value is adSaveCreateNotExists. With these options you can specify that an error occurs if
the specified file does not exist. You can also specify that SaveToFile overwrites the current contents of an
existing file.
NOTE
If you overwrite an existing file (when adSaveCreateOverwrite is set), SaveToFile truncates any bytes from the original
existing file that follow the new EOS.
Remarks
SaveToFile may be used to copy the contents of a Stream object to a local file. There is no change in the
contents or properties of the Stream object. The Stream object must be open before calling SaveToFile.
This method does not change the association of the Stream object to its underlying source. The Stream object
will still be associated with the original URL or Record that was its source when opened.
After a SaveToFile operation, the current position (Position) in the stream is set to the beginning of the stream
(0 ).
Applies To
Stream Object (ADO )
See Also
Open Method (ADO Stream)
Save Method
Type Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Indicates the operational type or data type of a Parameter, Field, or Property object.
Remarks
For Parameter objects, the Type property is read/write. For new Field objects that have been appended to
the Fields collection of a Record, Type is read/write only after the Value property for the Field has been
specified and the data provider has successfully added the new Field by calling the Update method of the
Fields collection.
For all other objects, the Type property is read-only.
Applies To
See Also
Type Property Example (Field) (VB )
Type Property Example (Property) (VC++)
RecordType Property (ADO )
Type Property (ADO Stream)
Update Resync Property-Dynamic (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Specifies whether the UpdateBatch method is followed by an implicit Resync method operation, and if so, the
scope of that operation.
Remarks
The values of ADCPROP_UPDATERESYNC_ENUM may be combined, except for adResyncAll which already
represents the combination of the rest of the values.
The constant adResyncConflicts stores the resync values as underlying values, but does not override pending
changes.
Update Resync is a dynamic property appended to the Recordset object Properties collection when the
CursorLocation property is set to adUseClient.
Applies To
Recordset Object (ADO )
ConnectionTimeout Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Indicates how long to wait while establishing a connection before terminating the attempt and generating an
error.
Remarks
Use the ConnectionTimeout property on a Connection object if delays from network traffic or heavy server use
make it necessary to abandon a connection attempt. If the time from the ConnectionTimeout property setting
elapses prior to the opening of the connection, an error occurs and ADO cancels the attempt. If you set the
property to zero, ADO will wait indefinitely until the connection is opened. Make sure the provider to which you
are writing code supports the ConnectionTimeout functionality.
The ConnectionTimeout property is read/write when the connection is closed and read-only when it is open.
Applies To
Connection Object (ADO )
See Also
ConnectionString, ConnectionTimeout, and State Properties Example (VB )
ConnectionString, ConnectionTimeout, and State Properties Example (VC++)
CommandTimeout Property (ADO )
StreamOpenOptionsEnum
10/1/2018 • 2 minutes to read • Edit Online
Specifies options for opening a Stream object. The values can be combined with an OR operation.
ADO/WFC Equivalent
These constants do not have ADO/WFC equivalents.
Applies To
Open Method (ADO Stream)
OpenSchema Method
11/13/2018 • 2 minutes to read • Edit Online
Syntax
Set recordset = connection.OpenSchema(QueryType, Criteria, SchemaID)
Return Value
Returns a Recordset object that contains schema information. The Recordset will be opened as a read-only,
static cursor. The QueryType determines what columns appear in the Recordset.
Parameters
QueryType
Any SchemaEnum value that represents the type of schema query to run.
Criteria
Optional. An array of query constraints for each QueryType option, as listed in SchemaEnum.
SchemaID
The GUID for a provider-schema query not defined by the OLE DB specification. This parameter is required if
QueryType is set to adSchemaProviderSpecific; otherwise, it is not used.
Remarks
The OpenSchema method returns self-descriptive information about the data source, such as what tables are in
the data source, the columns in the tables, and the data types supported.
The QueryType argument is a GUID that indicates the columns (schemas) returned. The OLE DB specification
has a full list of schemas.
The Criteria argument limits the results of a schema query. Criteria specifies an array of values that must occur
in a corresponding subset of columns, called constraint columns, in the resulting Recordset.
The constant adSchemaProviderSpecific is used for the QueryType argument if the provider defines its own
nonstandard schema queries outside those listed previously. When this constant is used, the SchemaID
argument is required to pass the GUID of the schema query to execute. If QueryType is set to
adSchemaProviderSpecific but SchemaID is not provided, an error will result.
Providers are not required to support all the OLE DB standard schema queries. Specifically, only
adSchemaTables, adSchemaColumns, and adSchemaProviderTypes are required by the OLE DB
specification. However, the provider is not required to support the Criteria constraints listed earlier for those
schema queries.
NOTE
Remote Data Service Usage The OpenSchema method is not available on a client-side Connection object.
NOTE
In Visual Basic, columns that have a four-byte unsigned integer (DBTYPE UI4) in the Recordset returned from the
OpenSchema method on the Connection object cannot be compared to other variables. For more information about
OLE DB data types, see Data Types in OLE DB (OLE DB) and Appendix A: Data Types in the Microsoft OLE DB
Programmer's Reference.
NOTE
Visual C/C++ Users When not using client-side cursors, retrieving the "ORDINAL_POSITION" of a column schema in ADO
returns a variant of type VT_R8 in MDAC 2.7, MDAC 2.8, and Windows Data Access Components (Windows DAC) 6.0,
while the type used in MDAC 2.6 was VT_I4. Programs written for MDAC 2.6 that only look for a variant returned of type
VT_I4 would get a zero for every ordinal if run under MDAC 2.7, MDAC 2.8, and Windows DAC 6.0 without modification.
This change was made because the data type that OLE DB returns is DBTYPE_UI4, and in the signed VT_I4 type there is
not enough room to contain all possible values without possibly truncation occurring and thereby causing a loss of data.
Applies To
Connection Object (ADO )
See Also
OpenSchema Method Example (VB )
OpenSchema Method Example (VC++)
Open Method (ADO Connection)
Open Method (ADO Record)
Open Method (ADO Recordset)
Open Method (ADO Stream)
Appendix A: Providers
Read Method
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Variant = Stream.Read ( NumBytes)
Parameters
NumBytes
Optional. A Long value that specifies the number of bytes to read from the file or the StreamReadEnum value
adReadAll, which is the default.
Return Value
The Read method reads a specified number of bytes or the entire stream from a Stream object and returns the
resulting data as a Variant.
Remarks
If NumBytes is more than the number of bytes left in the Stream, only the bytes remaining are returned. The
data read is not padded to match the length specified by NumBytes. If there are no bytes left to read, a variant
with a null value is returned. Read cannot be used to read backwards.
NOTE
NumBytes always measures bytes. For text Stream objects (Type is adTypeText), use ReadText.
Applies To
Stream Object (ADO )
See Also
ReadText Method
RecordCount Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Return Value
Returns a Long value that indicates the number of records in the Recordset.
Remarks
Use the RecordCount property to find out how many records are in a Recordset object. The property returns -
1 when ADO cannot determine the number of records or if the provider or cursor type does not support
RecordCount. Reading the RecordCount property on a closed Recordset causes an error.
Bookmarks or approximate positioning
If the Recordset object does support either bookmarks or approximate positioning, this property returns the
exact number of records in the Recordset. This property returns the exact number regardless of whether the
Recordset has been fully populated.
In contrast, if the Recordset object does not support either bookmarks or approximate positioning, accessing this
property might be a significant drain on resources. The drain occurs because all records must retrieved and
counted to return an accurate RecordCount value.
adBookmark related to bookmarks.
adApproxPosition relates to approximate positioning.
NOTE
In ADO versions 2.8 and earlier, the SQLOLEDB provider fetches all records when a server-side cursor is used, despite the
fact that it returns True for both Supports (adApproxPosition) and Supports (adBookmark).
The cursor type of the Recordset object affects whether the number of records can be determined. The
RecordCount property will return -1 for a forward-only cursor; the actual count for a static or keyset cursor;
and either -1 or the actual count for a dynamic cursor, depending on the data source.
Applies To
Recordset Object (ADO )
See Also
Filter and RecordCount Properties Example (VB )
Filter and RecordCount Properties Example (VC++)
AbsolutePosition Property (ADO )
PageCount Property (ADO )
ActiveCommand Property Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
Example
// BeginActiveCommandCpp.cpp
// compile with: /EHsc /c
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
#include "icrsint.h"
END_ADO_BINDING()
public:
CHAR m_szau_fname[21];
ULONG lau_fnameStatus;
CHAR m_szau_lname[41];
ULONG lau_lnameStatus;
};
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void ActiveCommandX();
void ActiveCommandXprint(_RecordsetPtr pRst);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
if (pstrRet == NULL)
return NULL;
if (!strrchr(strDest, '\n'))
// Exhaust the input buffer.
do {
fgets(strExBuff, sizeof(strExBuff), stdin);
} while (!strrchr(strExBuff, '\n'));
else
// Replace '\n' with '\0'
// Replace '\n' with '\0'
strDest[strrchr(strDest, '\n') - strDest] = '\0';
return pstrRet;
}
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
ActiveCommandX();
::CoUninitialize();
}
void ActiveCommandX() {
HRESULT hr = S_OK;
char * token1;
// Define ADO object pointers, initialize pointers on define. These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
_CommandPtr pCmd = NULL;
_RecordsetPtr pRstAuthors = NULL;
try {
// Open connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
TESTHR(pCmd.CreateInstance(__uuidof(Command)));
strName = ((_CommandPtr)pRst->GetActiveCommand())->GetParameters()->GetItem("LastName")->Value;
printf("Command text = '%s'\n", (LPCSTR)((_CommandPtr)pRst->GetActiveCommand())->CommandText);
printf("Parameter = '%s'\n", (LPCSTR)strName);
if (pRst->BOF)
printf("Name = '%s'not found.", (LPCSTR)strName);
else {
if ( (pConnection->Errors->Count) > 0) {
nCount = pConnection->Errors->Count;
// Collection ranges from 0 to (nCount - 1)
for ( i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s\n", pErr->Number, (LPCSTR)pErr->Description);
}
}
}
Sample Input
Ringer
Sample Output
Command text = 'SELECT * FROM authors WHERE au_lname = ?'
Parameter = 'Ringer'
Name = 'Anne Ringer'
See Also
ActiveCommand Property (ADO )
Recordset Object (ADO )
SearchDirectionEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.SearchDirection.BACKWARD
AdoEnums.SearchDirection.FORWARD
Applies To
Find Method (ADO )
ADO Dynamic Property Index
10/1/2018 • 3 minutes to read • Edit Online
Data providers, service providers, and service components can add dynamic properties to the Properties
collections of the unopened Connection and Recordset objects. A given provider may also insert additional
properties when these objects are opened. Some of these properties are listed in the ADO Dynamic Properties
section. More are listed under the specific providers in the Appendix A: Providers section.
The following tables are cross-indexes of the ADO and OLE DB names for each standard OLE DB provider
dynamic property. Your providers may add more properties than listed here. For the specific information about
provider-specific dynamic properties, see your provider documentation.
The OLE DB Programmer's Reference refers to an ADO property name by the term "Description." For more
information about these standard properties, search or browse the index in the OLE DB documentationfor the
OLE DB property by its name.
Location DBPROP_INIT_LOCATION
Mode DBPROP_INIT_MODE
Password DBPROP_AUTH_PASSWORD
Prompt DBPROP_INIT_PROMPT
User ID DBPROP_AUTH_USERID
IAccessor DBPROP_IACCESSOR
IChapteredRowset
IColumnsInfo DBPROP_ICOLUMNSINFO
IColumnsRowset DBPROP_ICOLUMNSROWSET
IConnectionPointContainer DBPROP_ICONNECTIONPOINTCONTAINER
IConvertType
ILockBytes DBPROP_ILOCKBYTES
IRowset DBPROP_IROWSET
IDBAsynchStatus DBPROP_IDBASYNCHSTATUS
IParentRowset
IRowsetChange DBPROP_IROWSETCHANGE
IRowsetExactScroll
IRowsetFind DBPROP_IROWSETFIND
IRowsetIdentity DBPROP_IROWSETIDENTITY
IRowsetInfo DBPROP_IROWSETINFO
IRowsetLocate DBPROP_IROWSETLOCATE
IRowsetRefresh DBPROP_IROWSETREFRESH
IRowsetResynch
IRowsetScroll DBPROP_IROWSETSCROLL
IRowsetUpdate DBPROP_IROWSETUPDATE
IRowsetView DBPROP_IROWSETVIEW
IRowsetIndex DBPROP_IROWSETINDEX
ISequentialStream DBPROP_ISEQUENTIALSTREAM
IStorage DBPROP_ISTORAGE
IStream DBPROP_ISTREAM
ADO PROPERTY NAME OLE DB PROPERTY NAME
ISupportErrorInfo DBPROP_ISUPPORTERRORINFO
Bookmarkable DBPROP_IROWSETLOCATE
Private1
Updatability DBPROP_UPDATABILITY
Properties
long GetAttributes( );
void PutAttributes( long plAttributes );
__declspec(property(get=GetAttributes,put=PutAttributes)) long
Attributes;
_bstr_t GetName( );
__declspec(property(get=GetName)) _bstr_t Name;
_variant_t GetValue( );
void PutValue( const _variant_t & pval );
__declspec(property(get=GetValue,put=PutValue)) _variant_t Value;
See Also
Property Object (ADO )
Mode Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Indicates the available permissions for modifying data in a Connection, Record, or Stream object.
Remarks
Use the Mode property to set or return the access permissions in use by the provider on the current
connection. You can set the Mode property only when the Connection object is closed.
For a Stream object, if the access mode is not specified, it is inherited from the source used to open the Stream
object. For example, if a Stream is opened from a Record object, by default it is opened in the same mode as
the Record.
This property is read/write while the object is closed and read-only while the object is open.
NOTE
Remote Data Service Usage When used on a client-side Connection object, the Mode property can only be set to
adModeUnknown.
Applies To
See Also
IsolationLevel and Mode Properties Example (VB )
IsolationLevel and Mode Properties Example (VC++)
Filter Property
10/1/2018 • 5 minutes to read • Edit Online
Remarks
Use the Filter property to selectively screen out records in a Recordset object. The filtered Recordset
becomes the current cursor. Other properties that return values based on the current cursor are affected,
such as AbsolutePosition Property (ADO ), AbsolutePage Property (ADO ), RecordCount Property (ADO ), and
PageCount Property (ADO ). Setting the Filter property to a specific new value moves the current record to
the first record that satisfies the new value.
The criteria string is made up of clauses in the form FieldName-Operator-Value (for example,
"LastName = 'Smith'" ). You can create compound clauses by concatenating individual clauses with AND (for
example, "LastName = 'Smith' AND FirstName = 'John'" ) or OR (for example,
"LastName = 'Smith' OR LastName = 'Jones'" ). For criteria strings, Use the following guidelines:
FieldName must be a valid field name from the Recordset. If the field name contains spaces, you
must enclose the name in square brackets.
Operator must be one of the following: <, >, <=, >=, <>, =, or LIKE.
Value is the value with which you will compare the field values (for example, 'Smith', #8/24/95#,
12.345, or $50.00). Use single quotes with strings and pound signs (#) with dates. For numbers, you
can use decimal points, dollar signs, and scientific notation. If Operator is LIKE, Value can use
wildcards. Only the asterisk (*) and percent sign (%) wild cards are allowed, and they must be the last
character in the string. Value cannot be null.
NOTE
To include single quotation marks (') in the filter Value, use two single quotation marks to represent one. For example,
to filter on O'Malley, the criteria string should be "col1 = 'O''Malley'" . To include single quotation marks at both
the beginning and the end of the filter value, enclose the string with pound signs (#). For example, to filter on '1', the
criteria string should be "col1 = #'1'#" .
There is no precedence between AND and OR. Clauses can be grouped within parentheses. However,
you cannot group clauses joined by an OR and then join the group to another clause with an AND, as
in the following code snippet:
(LastName = 'Smith' OR LastName = 'Jones') AND FirstName = 'John'
Instead, you would construct this filter as
(LastName = 'Smith' AND FirstName = 'John') OR (LastName = 'Jones' AND FirstName = 'John')
In a LIKE clause, you can use a wildcard at the beginning and end of the pattern. For example, you can
use LastName Like '*mit*' . Or with LIKE you can use a wildcard only at the end of the pattern. For
example, LastName Like 'Smit*' .
The filter constants make it easier to resolve individual record conflicts during batch update mode by
allowing you to view, for example, only those records that were affected during the last UpdateBatch Method
method call.
Setting the Filter property itself might fail due to a conflict with the underlying data. For example, this failure
can happen when a record has already been deleted by another user. In such a case, the provider returns
warnings to the Errors Collection (ADO ) collection, but does not halt program execution. An error at run time
occurs only if there are conflicts on all the requested records. Use the Status Property (ADO Recordset)
property to locate records with conflicts.
Setting the Filter property to a zero-length string ("") has the same effect as using the adFilterNone
constant.
Whenever the Filter property is set, the current record position moves to the first record in the filtered subset
of records in the Recordset. Similarly, when the Filter property is cleared, the current record position moves
to the first record in the Recordset.
Suppose that a Recordset is filtered based on a field of some variant type, such as the type sql_variant. An
error (DISP_E_TYPEMISMATCH or 80020005) occurs when the subtypes of the field and filter values used in
the criteria string do not match. For example, suppose:
A Recordset object (rs) contains a column (C ) of the sql_variant type.
And a field of this column has been assigned a value of 1 of the I4 type. The criteria string is set to
rs.Filter = "C='A'" on the field.
This configuration produces the error during run time. However, rs.Filter = "C=2" applied on the same
field will not produce any error. And the field is filtered out of the current record set.
See the Bookmark Property (ADO ) property for an explanation of bookmark values from which you can
build an array to use with the Filter property.
Only Filters in the form of criteria strings affect the contents of a persisted Recordset. An example of a
criteria string is OrderDate > '12/31/1999' . Filters created with an array of bookmarks, or using a value from
the FilterGroupEnum, do not affect the contents of the persisted Recordset. These rules apply to
Recordsets created with either client-side or server-side cursors.
NOTE
When you apply the adFilterPendingRecords flag to a filtered and modified Recordset in the batch update mode, the
resultant Recordset is empty if the filtering was based on the key field of a single-keyed table and the modification
was made on the key field values. The resultant Recordset will be non-empty if one of the following statements is
true:
Non keys + + +
Applies To
Recordset Object (ADO )
See Also
Filter and RecordCount Properties Example (VB ) Filter and RecordCount Properties Example (VC++) Clear
Method (ADO ) Optimize Property-Dynamic (ADO )
MoveFirst, MoveLast, MoveNext, and MovePrevious
Methods Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the MoveFirst, MoveLast, MoveNext, and MovePrevious methods to move the record pointer
of a Recordset based on the supplied command. The MoveAny function is required for this example to run.
Example
// MoveFirstMoveLastMoveNextSample.cpp
// compile with: /EHsc
#include <ole2.h>
#include <stdio.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void MoveFirstX();
void MoveAny(int intChoice, _RecordsetPtr pRstTemp);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
MoveFirstX();
::CoUninitialize();
}
void MoveFirstX() {
HRESULT hr = S_OK;
_RecordsetPtr pRstAuthors = NULL;
_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");
_bstr_t strMessage("UPDATE Titles SET Type = "
"'psychology' WHERE Type = 'self_help'");
int intCommand = 0;
try {
// Open recordset from Authors table.
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
pRstAuthors->CursorType = adOpenStatic;
scanf_s("%d", &intCommand);
catch(_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstTemp->GetActiveConnection();
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount - 1.
for ( long i = 0 ; i < nCount ; i++) {
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number, pErr->Description);
}
}
}
Input
See Also
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods (ADO )
Recordset Object (ADO )
ParameterAttributesEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.ParameterAttributes.SIGNED
AdoEnums.ParameterAttributes.NULLABLE
AdoEnums.ParameterAttributes.LONG
Applies To
Attributes Property (ADO )
Cancel Method Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Cancel method to cancel a command executing on a Connection object if the connection is
busy.
// CancelMethodExample.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include<conio.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void CancelX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
CancelX();
::CoUninitialize();
}
void CancelX() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace
_ConnectionPtr pConnection = NULL;
try {
// open a connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open(strCnn, "", "", adConnectUnspecified);
// If the command has NOT completed, cancel the execute and roll back the
// transaction. Otherwise, commit the transaction.
if ( (pConnection->GetState()) ) {
if ( (pConnection->GetState()) ) {
pConnection->Cancel();
pConnection->RollbackTrans();
booChanged = FALSE;
printf("Update canceled.\n");
printf("GetState = %d\n", pConnection->GetState());
}
else {
pConnection->CommitTrans();
booChanged = TRUE;
printf("Update complete.\n");
}
// If the change was made, restore the data because this is a demonstration.
if (booChanged) {
pConnection->Execute(strCmdRestore, NULL, 0);
printf("Data restored.\n");
}
}
catch(_com_error &e) {
// Notify user of any errors that result from executing the query.
// Pass a connection pointer accessed from the Connection.
PrintProviderError(pConnection);
PrintComError(e);
}
if ( (pConnection->Errors->Count) > 0 ) {
long nCount = pConnection->Errors->Count;
See Also
Cancel Method (ADO )
Connection Object (ADO )
Field (ADO - WFC Syntax)
11/28/2018 • 2 minutes to read • Edit Online
package com.ms.wfc.data
Methods
Properties
(For more information, see the documentation for the com.ms.wfc.data.IDataFormat interface.)
See Also
Field Object
EventReasonEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.EventReason.ADDNEW
AdoEnums.EventReason.CLOSE
AdoEnums.EventReason.DELETE
AdoEnums.EventReason.FIRSTCHANGE
AdoEnums.EventReason.MOVE
AdoEnums.EventReason.MOVEFIRST
AdoEnums.EventReason.MOVELAST
AdoEnums.EventReason.MOVENEXT
AdoEnums.EventReason.MOVEPREVIOUS
AdoEnums.EventReason.REQUERY
AdoEnums.EventReason.RESYNCH
AdoEnums.EventReason.UNDOADDNEW
AdoEnums.EventReason.UNDODELETE
AdoEnums.EventReason.UNDOUPDATE
AdoEnums.EventReason.UPDATE
Applies To
Gets or sets an OLE DB Rowset object from/on an ADORecordsetConstruction object. When you use
put_Rowset, the rowset is turned into an ADO Recordset object.
Read/write.
Syntax
HRESULT get_Rowset([out, retval] IUnknown** ppRowset);
HRESULT put_Rowset([in] IUnknown* pRowset);
Parameters
ppRowset
Pointer to an OLE DB Rowset object.
PRowset
An OLE DB Rowset object.
Return Values
This property method returns the standard HRESULT values, including S_OK and E_FAIL.
Applies To
ADORecordsetConstruction Interface
Delete Method Example (VC++)
10/1/2018 • 3 minutes to read • Edit Online
This example uses the Delete method to remove a specified record from a Recordset.
Example
// DeleteMethodExample.cpp
// compile with: /EHsc /c
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <stdio.h>
#include <ole2.h>
#include <conio.h>
#include "icrsint.h"
// This Class extracts titleid, lorange, hirange and royalty from the "roysched" table.
class CRoySchedRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CRoySchedRs)
END_ADO_BINDING()
public:
CHAR m_sz_titleid[10];
ULONG lemp_titleidStatus;
ULONG m_sz_lorange;
ULONG lemp_lorangeStatus;
ULONG m_sz_hirange;
ULONG lemp_hirangeStatus;
ULONG m_sz_royalty;
ULONG lemp_royaltyStatus;
};
// Function Declarations.
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void DeleteX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
inline char* mygets(char* strDest, int n) {
char strExBuff[10];
char* pstrRet = fgets(strDest, n, stdin);
if (pstrRet == NULL)
return NULL;
if (!strrchr(strDest, '\n'))
// Exhaust the input buffer.
do {
do {
fgets(strExBuff, sizeof(strExBuff), stdin);
} while (!strrchr(strExBuff, '\n'));
else
// Replace '\n' with '\0'
strDest[strrchr(strDest, '\n') - strDest] = '\0';
return pstrRet;
}
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
DeleteX();
::CoUninitialize();
}
void DeleteX() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace.
_RecordsetPtr pRstRoySched = NULL;
try {
// Open RoySched table
TESTHR(pRstRoySched.CreateInstance(__uuidof(Recordset)));
pRstRoySched->CursorLocation = adUseClient;
pRstRoySched->CursorType = adOpenStatic;
pRstRoySched->LockType = adLockBatchOptimistic;
while(!(pRstRoySched->EndOfFile)) {
printf("%s\n", royschrs.lemp_titleidStatus == adFldOK ?
royschrs.m_sz_titleid : "<NULL>");
pRstRoySched->MoveNext();
}
if ( pRstRoySched->RecordCount != 0 ) {
intLoRange = royschrs.m_sz_lorange;
longHiRange = royschrs.m_sz_hirange;
intRoyalty = royschrs.m_sz_royalty;
while ( !(pRstRoySched->EndOfFile) ) {
printf("\n%s", royschrs.lemp_titleidStatus == adFldOK ?
royschrs.m_sz_titleid : "<NULL>");
pRstRoySched->MoveNext();
}
TESTHR(picRs->AddNew(&royschrs));
pRstRoySched->UpdateBatch(adAffectCurrent);
}
}
catch(_com_error &e) {
// Display errors, if any. Pass connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstRoySched->GetActiveConnection();
if (pRstRoySched)
if (pRstRoySched->State == adStateOpen)
pRstRoySched->Close();
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
Sample Input
TC4203
Sample Output
Before delete there are 7 titles with 20 percent royalty :
BU2075
MC3021
TC3218
BU1111
MC2222
TC4203
BU7832
See Also
Delete Method (ADO Recordset)
Recordset Object (ADO )
Source Property Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Source property by opening three Recordset objects based on different data
sources.
'BeginSourceVB
' Use the Source property to display the source of each recordset.
MsgBox "rstTitles source: " & vbCr & _
rstTitles.Source & vbCr & vbCr & _
"rstPublishers source: " & vbCr & _
rstPublishers.Source & vbCr & vbCr & _
rstPublishers.Source & vbCr & vbCr & _
"rstPublishersDirect source: " & vbCr & _
rstPublishersDirect.Source & vbCr & vbCr & _
"rstTitlesPublishers source: " & vbCr & _
rstTitlesPublishers.Source
' clean up
rstTitles.Close
rstPublishers.Close
rstTitlesPublishers.Close
Cnxn.Close
Set rstTitles = Nothing
Set rstPublishers = Nothing
Set rstTitlesPublishers = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstTitles Is Nothing Then
If rstTitles.State = adStateOpen Then rstTitles.Close
End If
Set rstTitles = Nothing
See Also
Recordset Object (ADO )
Source Property (ADO Recordset)
Fields Collection (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
A Recordset object has a Fields collection made up of Field objects. Each Field object corresponds to a
column in the Recordset. You can populate the Fields collection before opening the Recordset by calling
the Refresh method on the collection.
NOTE
See the Field object topic for a more detailed explanation of how to use Field objects.
The Fields collection has an Append method, which provisionally creates and adds a Field object to the
collection, and an Update method, which finalizes any additions or deletions.
A Record object has two special fields that can be indexed with FieldEnum constants. One constant
accesses a field containing the default stream for the Record, and the other accesses a field containing
the absolute URL string for the Record.
Certain providers (for example, the Microsoft OLE DB Provider for Internet Publishing) may populate the
Fields collection with a subset of available fields for the Record or Recordset. Other fields will not be
added to the collection until they are first referenced by name or indexed by your code.
If you attempt to reference a nonexistent field by name, a new Field object will be appended to the Fields
collection with a Status of adFieldPendingInsert. When you call Update, ADO will create a new field in
your data source if allowed by your provider.
This section contains the following topic.
Fields Collection Properties, Methods, and Events
See Also
Field Object
Clone Method Example (VC++)
10/1/2018 • 3 minutes to read • Edit Online
This example uses the Clone method to create copies of a Recordset and then lets the user position the record
pointer of each copy independently.
// BeginCloneCpp.cpp
// compile with: /EHsc /c
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <stdio.h>
#include <ole2.h>
#include <conio.h>
#include "icrsint.h"
END_ADO_BINDING()
public:
CHAR m_szS_stor_name[150];
ULONG lS_stor_nameStatus;
};
// Function Declarations.
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void CloneX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
if (pstrRet == NULL)
return NULL;
if (!strrchr(strDest, '\n'))
// Exhaust the input buffer.
do {
fgets(strExBuff, sizeof(strExBuff), stdin);
} while (!strrchr(strExBuff, '\n'));
else
// Replace '\n' with '\0'
strDest[strrchr(strDest, '\n') - strDest] = '\0';
return pstrRet;
}
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
CloneX();
::CoUninitialize();
}
}
void CloneX() {
// Define ADO object pointers, initialize pointers on define. These are in the ADODB:: namespace.
_RecordsetPtr arstStores[3];
try {
// Open recordset as a static cursor type recordset.
arstStores[0].CreateInstance(__uuidof(Recordset));
arstStores[0]->CursorType = adOpenStatic;
arstStores[0]->LockType = adLockBatchOptimistic;
TESTHR(arstStores[0]->Open(strSQL,strCnn, adOpenStatic,
adLockBatchOptimistic, adCmdText));
while (boolFlag) {
// Loop through the array so that on each pass, the user is searching a
// different copy of the same Recordset.
for (intLoop = 1; intLoop <= 3 ; intLoop++) {
// Ask for search string while showing where
// the current record pointer is for each Recordset.
printf("Recordsets from stores table:\n");
if (arstStores[intLoop1]->EndOfFile) {
arstStores[intLoop1]->Filter = (long)adFilterNone;
arstStores[intLoop1]->MoveLast();
}
}
} // End of While Loop
}
catch(_com_error &e) {
// Notify the user of errors if any.
_variant_t vtConnect;
vtConnect = arstStores[0]->GetActiveConnection();
switch(vtConnect.vt) {
case VT_BSTR:
PrintComError(e);
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}
Syntax
Stream.WriteText Data, Options
Parameters
Data
A String value that contains the text in characters to be written.
Options
Optional. A StreamWriteEnum value that specifies whether a line separator character must be written at the end
of the specified string.
Remarks
Specified strings are written to the Stream object without any intervening spaces or characters between each
string.
The current Position is set to the character following the written data. The WriteText method does not truncate
the rest of the data in a stream. If you want to truncate these characters, call SetEOS.
If you write past the current EOS position, the Size of the Stream will be increased to contain any new
characters, and EOS will move to the new last byte in the Stream.
NOTE
The WriteText method is used with text streams (Type is adTypeText). For binary streams ( Type is adTypeBinary), use
Write.
Applies To
Stream Object (ADO )
See Also
Write Method
AbsolutePosition Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
In order to set the AbsolutePosition property, ADO requires that the OLE DB provider you are using
implement the IRowsetLocate:IRowset interface.
Accessing the AbsolutePosition property of a Recordset that was opened with either a forward-only or
dynamic cursor raises the error adErrFeatureNotAvailable. With other cursor types, the correct position will
be returned as long as the OLE DB provider supports the IRowsetScroll:IRowsetLocate interface. If the
provider does not support the IRowsetScroll interface, the property is set to adPosUnknown. See the
documentation for your provider to determine whether it supports IRowsetScroll.
Use the AbsolutePosition property to move to a record based on its ordinal position in the Recordset object,
or to determine the ordinal position of the current record. The provider must support the appropriate
functionality for this property to be available.
Like the AbsolutePage property, AbsolutePosition is 1-based and equals 1 when the current record is the first
record in the Recordset. You can obtain the total number of records in the Recordset object from the
RecordCount property.
When you set the AbsolutePosition property, even if it is to a record in the current cache, ADO reloads the
cache with a new group of records starting with the record you specified. The CacheSize property determines
the size of this group.
NOTE
You should not use the AbsolutePosition property as a surrogate record number. The position of a given record
changes when you delete a preceding record. There is also no assurance that a given record will have the same
AbsolutePosition if the Recordset object is requeried or reopened. Bookmarks are still the recommended way of
retaining and returning to a given position and are the only way of positioning across all types of Recordset objects.
Applies To
Recordset Object (ADO )
See Also
AbsolutePosition and CursorLocation Properties Example (VB )
AbsolutePosition and CursorLocation Properties Example (VC++)
AbsolutePage Property (ADO )
RecordCount Property (ADO )
RecordType Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Return Value
Returns a RecordTypeEnum value.
Remarks
The RecordType property is read-only.
Applies To
Record Object (ADO )
See Also
Type Property (ADO )
Type Property (ADO Stream)
ADO Code Examples VBScript
10/1/2018 • 2 minutes to read • Edit Online
Use the following code examples to learn about how to use the ADO methods when writing in Microsoft® Visual
Basic® Scripting Edition (VBScript).
NOTE
Paste the entire code example, from beginning to end, into your code editor. The example may not run correctly if partial
examples are used or if paragraph formatting is lost.
Methods
AddNew Method Example
Clone Method Example
Delete Method Example
Execute, Requery, and Clear Methods Example
Move Method Example
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods Example
Open and Close Methods Example
See Also
ADO Code Examples in Visual Basic
ADO Code Examples in Visual C++
Appendix D: ADO Samples
Delete Method Example (VBScript)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Delete method to remove a specified record from a Recordset.
Use the following example in an Active Server Page (ASP ). To view this fully functional example, you must either
have the data source AdvWorks.mdb (installed with the SDK) located at C:\Program Files\Microsoft Platform
SDK\Samples\DataAccess\Rds\RDSTest\advworks.mdb or edit the path in the example code to reflect the actual
location of this file. This is a Microsoft Access database file.
Use Find to locate the file Adovbs.inc and place it in the directory you plan to use. Cut and paste the following
code into Notepad or another text editor, and save it as DeleteVBS.asp. You can view the result in any client
browser.
To exercise the example, try using the AddNew example first to add some records. Then you can try to delete
them. View the result in any client browser.
<BODY>
<H3>ADO Delete Method</H3>
<%
' to integrate this code replace the DataSource value in the connection string
rsCustomers.Move CInt(Moves)
If Not rsCustomers.EOF or rsCustomers.BOF Then
' handle any db errors
On Error Resume Next
rsCustomers.Delete 1
If Cnxn.Errors.Count <> 0 Then
Response.Write "Cannot delete since there are related records in other tables."
Response.End
End If
rsCustomers.MoveFirst
On Error GoTo 0
Else
Response.Write "Not a Valid Record Number"
rsCustomers.MoveFirst
End If
End If
%>
<%
' Display ADO Data from Customer Table
' Loop through Recordset adding one row to HTML Table each pass
Dim iCount
iCount = 0
Do Until rsCustomers.EOF %>
<TR>
<TD> <%= CStr(iCount) %>
<TD> <%= rsCustomers("CompanyName")%> </TD>
<TD> <%= rsCustomers("ContactName")%> </TD>
<TD> <%= rsCustomers("City")%> </TD>
</TR>
<%
iCount = iCount + 1
rsCustomers.MoveNext
Loop
%>
</TABLE>
<!-- Do Client side Input Data Validation Move to named record and Delete it -->
<Center>
<H4>Clicking Button Will Remove Designated Record</H4>
<H5>There are <%=rsCustomers.RecordCount%> Records in this Set</H5>
</BODY>
<%
' clean up
If rsCustomers.State = adStateOpen then
rsCustomers.Close
End If
If Cnxn.State = adStateOpen then
Cnxn.Close
End If
%>
</HTML>
<!-- EndDeleteVBS -->
See Also
Delete Method (ADO Recordset)
Recordset Object (ADO )
EOS and LineSeparator Properties and SkipLine
Method Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates how to manipulate text streams one line at a time. The effect of changing the line
separator from the default carriage return/linefeed (adCRLF) to simply linefeed (adLF) or carriage return (adCR)
is shown.
'BeginSkipLineVB
Private Sub cmdSkipLine_Click()
On Error GoTo ErrorHandler
'Declare variables
Dim i As Integer
Dim objStream As Stream
Dim strLine, strChar As String
' clean up
objStream.Close
Set objStream = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not objStream Is Nothing Then
If objStream.State = adStateOpen Then objStream.Close
End If
Set objStream = Nothing
See Also
EOS Property
LineSeparator Property (ADO )
SkipLine Method
Parameter (ADO for Visual C++ Syntax)
10/1/2018 • 2 minutes to read • Edit Online
Methods
AppendChunk(VARIANT Val)
Properties
get_Attributes(LONG *plParmAttribs)
put_Attributes(LONG lParmAttribs)
get_Direction(ParameterDirectionEnum *plParmDirection)
put_Direction(ParameterDirectionEnum lParmDirection)
get_Name(BSTR *pbstr)
put_Name(BSTR bstr)
get_NumericScale(BYTE *pbScale)
put_NumericScale(BYTE bScale)
get_Precision(BYTE *pbPrecision)
put_Precision(BYTE bPrecision)
get_Size(long *pl)
put_Size(long l)
get_Type(DataTypeEnum *psDataType)
put_Type(DataTypeEnum sDataType)
get_Value(VARIANT *pvar)
put_Value(VARIANT val)
See Also
Parameter Object
Resync Method
10/1/2018 • 2 minutes to read • Edit Online
Refreshes the data in the current Recordset object, or Fields collection of a Record object, from the underlying
database.
Syntax
Recordset.Resync AffectRecords, ResyncValues Record.Fields.Resync ResyncValues
Parameters
AffectRecords
Optional. An AffectEnum value that determines how many records the Resync method will affect. The default
value is adAffectAll. This value is not available with the Resync method of the Fields collection of a Record
object.
ResyncValues
Optional. A ResyncEnum value that specifies whether underlying values are overwritten. The default value is
adResyncAllValues.
Remarks
Recordset
Use the Resync method to resynchronize records in the current Recordset with the underlying database.
This is useful if you are using either a static or forward-only cursor, but you want to see any changes in the
underlying database.
If you set the CursorLocation property to adUseClient, Resync is only available for non-read-only
Recordset objects.
Unlike the Requery method, the Resync method does not re-execute the Recordset object's underlying
command. New records in the underlying database will not be visible.
If the attempt to resynchronize fails because of a conflict with the underlying data (for example, a record has
been deleted by another user), the provider returns warnings to the Errors collection and a run-time error
occurs. Use the Filter property ( adFilterConflictingRecords) and the Status property to locate records with
conflicts.
If the Unique Table and Resync Command dynamic properties are set, and the Recordset is the result of
executing a JOIN operation on multiple tables, then the Resync method will execute the command given in
the Resync Command property only on the table named in the Unique Table property.
Fields
Use the Resync method to resynchronize the values of the Fields collection of a Record object with the
underlying data source. The Count property is not affected by this method.
If ResyncValues is set to adResyncAllValues (the default value), the UnderlyingValue, Value, and
OriginalValue properties of Field objects in the collection are synchronized. If ResyncValues is set to
adResyncUnderlyingValues, only the UnderlyingValue property is synchronized.
The value of the Status property for each Field object at the time of the call also affects the behavior of
Resync. For Field objects that have Status values of adFieldPendingUnknown or adFieldPendingInsert,
Resync has no effect. For Status values of adFieldPendingChange or adFieldPendingDelete, Resync
synchronizes data values for fields that still exist at the data source.
Resync will not modify Status values of Field objects unless an error occurs when Resync is called. For
example, if the field no longer exists, the provider will return an appropriate Status value for the Field object,
such as adFieldDoesNotExist. Returned Status values can be logically combined within the value of the
Status property.
Applies To
See Also
Resync Method Example (VB )
Resync Method Example (VC++)
Clear Method (ADO )
UnderlyingValue Property
ActualSize Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the ActualSize property to return the actual length of a Field object's value. For all fields, the ActualSize
property is read-only. If ADO cannot determine the length of the Field object's value, the ActualSize property
returns adUnknown.
The ActualSize and DefinedSize properties are different, as shown in the following example. A Field object with
a declared type of adVarChar and a maximum length of 50 characters returns a DefinedSize property value of
50, but the ActualSize property value it returns is the length of the data stored in the field for the current record.
Fields with a DefinedSize greater than 255 bytes are treated as variable length columns.
Applies To
Field Object
See Also
ActualSize and DefinedSize Properties Example (VB )
ActualSize and DefinedSize Properties Example (VC++)
DefinedSize Property
Version Property Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Version property of a Connection object to display the current ADO version. It also uses
several dynamic properties to show:
the current DBMS name and version.
OLE DB version.
provider name and version.
ODBC version.
ODBC driver name and version.
'BeginVersionVB
Public Sub Main()
On Error GoTo ErrorHandler
MsgBox strVersionInfo
' clean up
Cnxn.Close
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not Cnxn Is Nothing Then
If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing
See Also
Connection Object (ADO )
Version Property (ADO )
SetEOS Method
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Stream.SetEOS
Remarks
SetEOS updates the value of the EOS property, by making the current Position the end of the stream. Any bytes
or characters following the current position are truncated.
Because Write, WriteText, and CopyTo do not truncate any extra values in existing Stream objects, you can
truncate these bytes or characters by setting the new end-of-stream position with SetEOS.
Cau t i on
If you set EOS to a position before the actual end of the stream, you will lose all data after the new EOS position.
Applies To
Stream Object (ADO )
OpenSchema Method Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the OpenSchema method to display the name and type of each table in the Pubs database.
// OpenSchemaMethodExample.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <oleauto.h>
#include <conio.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void OpenSchemaX();
void OpenSchemaX2();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
OpenSchemaX();
OpenSchemaX2();
::CoUninitialize();
}
void OpenSchemaX() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
_RecordsetPtr pRstSchema = NULL;
try {
// Open connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open (strCnn, "", "", adConnectUnspecified);
pRstSchema = pConnection->OpenSchema(adSchemaTables);
while ( !(pRstSchema->EndOfFile) ) {
_bstr_t table_name = pRstSchema->Fields->GetItem("TABLE_NAME")->Value;
pRstSchema->MoveNext();
}
}
catch (_com_error &e) {
// Display errors, if any. Pass connection pointer accessed from the Connection.
PrintProviderError(pConnection);
PrintComError(e);
}
}
void OpenSchemaX2() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace.
_ConnectionPtr pConnection2 = NULL;
_RecordsetPtr pRstSchema = NULL;
try {
// Open connection.
TESTHR(pConnection2.CreateInstance(__uuidof(Connection)));
pConnection2->Open (strCnn, "", "", adConnectUnspecified);
long ix;
ix = 0;
SafeArrayPutElement(psa, &ix, &var);
ix= 1;
SafeArrayPutElement(psa, &ix, &var);
ix = 2;
SafeArrayPutElement(psa, &ix, &var);
var.vt = VT_BSTR;
char * s1 = "VIEW";
_bstr_t str = s1;
var.bstrVal = str;
ix = 3;
SafeArrayPutElement(psa, &ix, &var);
Array.vt = VT_ARRAY|VT_VARIANT;
Array.parray = psa;
pRstSchema = pConnection2->OpenSchema(adSchemaTables,&Array);
while(!(pRstSchema->EndOfFile))
{
printf("Table Name: %s\n",
(LPCSTR) (_bstr_t) pRstSchema->Fields->GetItem("TABLE_NAME")->Value);
pRstSchema->MoveNext();
}
} // End Try statement.
catch (_com_error &e) {
// Display errors, if any. Pass connection pointer accessed from the Connection.
PrintProviderError(pConnection2);
PrintComError(e);
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number, pErr->Description);
}
}
}
See Also
OpenSchema Method
FieldAttributeEnum
11/28/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.FieldAttribute.CACHEDEFERRED
AdoEnums.FieldAttribute.FIXED
AdoEnums.FieldAttribute.ISNULLABLE
AdoEnums.FieldAttribute.LONG
AdoEnums.FieldAttribute.MAYBENULL
AdoEnums.FieldAttribute.MAYDEFER
AdoEnums.FieldAttribute.NEGATIVESCALE
AdoEnums.FieldAttribute.ROWID
CONSTANT
AdoEnums.FieldAttribute.ROWVERSION
AdoEnums.FieldAttribute.UNKNOWNUPDATABLE
AdoEnums.FieldAttribute.UNSPECIFIED
AdoEnums.FieldAttribute.UPDATABLE
Applies To
Indicates the value of a Field that existed in the record before any changes were made.
Return Value
Returns a Variant value that represents the value of a field prior to any change.
Remarks
Use the OriginalValue property to return the original field value for a field from the current record.
In immediate update mode (in which the provider writes changes to the underlying data source after you call the
Update method), the OriginalValue property returns the field value that existed prior to any changes (that is,
since the last Update method call). This is the same value that the CancelUpdate method uses to replace the
Value property.
In batch update mode (in which the provider caches multiple changes and writes them to the underlying data
source only when you call the UpdateBatch method), the OriginalValue property returns the field value that
existed prior to any changes (that is, since the last UpdateBatch method call). This is the same value that the
CancelBatch method uses to replace the Value property. When you use this property with the UnderlyingValue
property, you can resolve conflicts that arise from batch updates.
Record
For Record objects, the OriginalValue property will be empty for fields added before Update is called.
Applies To
Field Object
See Also
OriginalValue and UnderlyingValue Properties Example (VB )
OriginalValue and UnderlyingValue Properties Example (VC++)
UnderlyingValue Property
Supports Method Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Supports method to display the options supported by a recordset opened with different
cursor types. The DisplaySupport function is required for this example to run.
// SupportsMethodExample.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <stdio.h>
#include <ole2.h>
#include <conio.h>
// Function Declarations.
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void SupportsX();
void DisplaySupport(_RecordsetPtr pRstTemp);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
SupportsX();
::CoUninitialize();
}
void SupportsX() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace.
_RecordsetPtr pRstTitles = NULL;
try {
// Open a recordset from Titles table
TESTHR(pRstTitles.CreateInstance(__uuidof(Recordset)));
switch(aintCursorType[intIndex]) {
case adOpenForwardOnly:
printf("\nForwardOnly cursor supports:\n");
printf("\nForwardOnly cursor supports:\n");
break;
case adOpenKeyset:
printf("\nKeyset cursor supports:\n");
break;
case adOpenDynamic:
printf("\nDynamic cursor supports:\n");
break;
case adOpenStatic:
printf("\nStatic cursor supports:\n");
break;
default :
break;
}
DisplaySupport(pRstTitles);
}
}
catch(_com_error &e) {
// Display errors, if any. Pass connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstTitles->GetActiveConnection();
if (booSupports) {
switch(alngConstants[intIndex]) {
case adAddNew :
printf("\n AddNew");
break;
break;
case adApproxPosition :
printf("\n AbsolutePosition and AbsolutePage");
break;
case adBookmark :
printf("\n Bookmark");
break;
case adDelete :
printf("\n Delete");
break;
case adFind :
printf("\n Find");
break;
case adHoldRecords :
printf("\n Holding Records");
break;
case adMovePrevious :
printf("\n MovePrevious and Move");
break;
case adNotify :
printf("\n Notifications");
break;
case adResync :
printf("\n Resyncing data");
break;
case adUpdate :
printf("\n Update");
break;
case adUpdateBatch :
printf("\n Batch updating");
break;
default :
break;
}
}
}
}
if ( (pConnection->Errors->Count) > 0 ) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
Recordset Object (ADO )
Supports Method
RecordCreateOptionsEnum
10/1/2018 • 2 minutes to read • Edit Online
Specifies whether an existing Record should be opened or a new Record created for the Record object Open
method. The values can be combined with an AND operator.
ADO/WFC Equivalent
These constants do not have ADO/WFC equivalents.
Applies To
Open Method (ADO Record)
MoveRecord Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Record.MoveRecord (Source, Destination, UserName, Password, Options, Async)
Parameters
Source
Optional. A String value that contains a URL identifying the Record to be moved. If Source is omitted or
specifies an empty string, the object represented by this Record is moved. For example, if the Record represents
a file, the contents of the file are moved to the location specified by Destination.
Destination
Optional. A String value that contains a URL specifying the location where Source will be moved.
UserName
Optional. A String value that contains the user ID that, if needed, authorizes access to Destination.
Password
Optional. A String that contains the password that, if needed, verifies UserName.
Options
Optional. A MoveRecordOptionsEnum value whose default value is adMoveUnspecified. Specifies the
behavior of this method.
Async
Optional. A Boolean value that, when True, specifies this operation should be asynchronous.
Return Value
A String value. Typically, the value of Destination is returned. However, the exact value returned is provider-
dependent.
Remarks
The values of Source and Destination must not be identical; otherwise, a run-time error occurs. At least the
server, path, and resource names must differ.
For files moved using the Internet Publishing Provider, this method updates all hypertext links in files being
moved unless otherwise specified by Options. This method fails if Destination identifies an existing object (for
example, a file or directory), unless adMoveOverWrite is specified.
NOTE
Use the adMoveOverWrite option judiciously. For example, specifying this option when moving a file to a directory will
delete the directory and replace it with the file.
Certain attributes of the Record object, such as the ParentURL property, will not be updated after this operation
completes. Refresh the Record object's properties by closing the Record, then re-opening it with the URL of the
location where the file or directory was moved.
If this Record was obtained from a Recordset, the new location of the moved file or directory will not be
reflected immediately in the Recordset. Refresh the Recordset by closing and re-opening it.
NOTE
URLs using the http scheme will automatically invoke the Microsoft OLE DB Provider for Internet Publishing. For more
information, see Absolute and Relative URLs.
Applies To
Record Object (ADO )
See Also
Move Method (ADO )
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods (ADO )
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods (RDS )
Parameter (Visual C++ Syntax Index with #import)
10/1/2018 • 2 minutes to read • Edit Online
Methods
HRESULT AppendChunk( const _variant_t & Val );
Properties
long GetAttributes( );
void PutAttributes( long plParmAttribs );
__declspec(property(get=GetAttributes,put=PutAttributes)) long
Attributes;
_bstr_t GetName( );
void PutName( _bstr_t pbstr );
__declspec(property(get=GetName,put=PutName)) _bstr_t Name;
long GetSize( );
void PutSize( long pl );
__declspec(property(get=GetSize,put=PutSize)) long Size;
_variant_t GetValue( );
void PutValue( const _variant_t & pvar );
__declspec(property(get=GetValue,put=PutValue)) _variant_t Value;
See Also
Parameter Object
Update Method
10/1/2018 • 2 minutes to read • Edit Online
Saves any changes you make to the current row of a Recordset object, or the Fields collection of a Record
object.
Syntax
recordset.Update Fields, Values
record.Fields.Update
Parameters
Fields
Optional. A Variant that represents a single name, or a Variant array that represents names or ordinal
positions of the field or fields you wish to modify.
Values
Optional. A Variant that represents a single value, or a Variant array that represents values for the field
or fields in the new record.
Remarks
Recordset
Use the Update method to save any changes you make to the current record of a Recordset object since
calling the AddNew method or since changing any field values in an existing record. The Recordset
object must support updates.
To set field values, do one of the following:
Assign values to a Field object's Value property and call the Update method.
Pass a field name and a value as arguments with the Update call.
Pass an array of field names and an array of values with the Update call.
When you use arrays of fields and values, there must be an equal number of elements in both arrays.
Also, the order of field names must match the order of field values. If the number and order of fields and
values do not match, an error occurs.
If the Recordset object supports batch updating, you can cache multiple changes to one or more records
locally until you call the UpdateBatch method. If you are editing the current record or adding a new
record when you call the UpdateBatch method, ADO will automatically call the Update method to save
any pending changes to the current record before transmitting the batched changes to the provider.
If you move from the record you are adding or editing before calling the Update method, ADO will
automatically call Update to save the changes. You must call the CancelUpdate method if you want to
cancel any changes made to the current record or discard a newly added record.
The current record remains current after you call the Update method.
Record
The Update method finalizes additions, deletions, and updates to fields in the Fields collection of a
Record object.
For example, fields deleted with the Delete method are marked for deletion immediately but remain in
the collection. The Update method must be called to actually delete these fields from the provider's
collection.
Applies To
See Also
Update and CancelUpdate Methods Example (VB )
Update and CancelUpdate Methods Example (VC++)
AddNew Method (ADO )
CancelUpdate Method (ADO )
EditMode Property
UpdateBatch Method
Collections (ADO for Visual C++ Syntax)
10/1/2018 • 2 minutes to read • Edit Online
Parameters
Methods
Append(IDispatch *Object);
Delete(VARIANT Index);
Refresh(void);
get_Count(long *c);
get_Item(VARIANT Index, _ADOParameter **ppvObject);
Fields
Methods
get_Count(long *c);
get_Item(VARIANT Index, ADOField **ppvObject);
Errors
Methods
Clear(void);
Refresh(void);
get_Count(long *c);
get_Item(VARIANT Index, ADOError **ppvObject);
Properties
Methods
Refresh(void);
get_Count(long *c);
get_Item(VARIANT Index, ADOProperty **ppvObject);
See Also
Errors Collection (ADO )
Fields Collection (ADO )
Parameters Collection (ADO )
Properties Collection (ADO )
Read, ReadText, Write, and WriteText Methods
Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates how to read the contents of a text box into both a text Stream and a binary Stream.
Other properties and methods shown include Position, Size, Charset, and SetEOS.
'BeginReadVB
Private Sub cmdRead_Click()
On Error GoTo ErrorHandler
'Declare variables
Dim objStream As Stream
Dim varA As Variant
Dim bytA() As Byte
Dim i As Integer
Dim strBytes As String
' clean up
objStream.Close
Set objStream = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not objStream Is Nothing Then
If objStream.State = adStateOpen Then objStream.Close
End If
Set objStream = Nothing
See Also
Charset Property (ADO )
Position Property (ADO )
Read Method
ReadText Method
SetEOS Method
Size Property (ADO Stream)
Stream Object (ADO )
Write Method
WriteText Method
Reshape Name Property-Dynamic (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Return Values
Returns a String value that is the name of the Recordset.
Remarks
Names persist for the duration of the connection or until the Recordset is closed.
The Reshape Name property is primarily intended for use with the re-shaping feature of the Microsoft Data
Shaping Service for OLE DB service provider. Names must be unique to participate in re-shaping.
This property is read-only, but can be set indirectly when a Recordset is created. For example, if a clause of a
Shape command creates a Recordset and gives it an alias name by using the AS keyword, the alias is assigned to
the Reshape Name property. If no alias is declared, the Reshape Name property is assigned a unique name
generated by the data shaping service. If the alias name is the same as the name of an existing Recordset, neither
Recordset can be reshaped until one of them is released. The default behavior can be changed by setting a unique
name in the Reshape Name property on the ADO connection to True. Setting this property gives the data shaping
service permission to change the user assigned name, if necessary, to ensure uniqueness. For more information
about reshaping, see Microsoft Data Shaping Service for OLE DB (ADO Service Provider).
Use the Reshape Name property when you want to refer to a Recordset in a Shape command, or when you do
not know the name because it was generated by the Data Shaping Service. In that case, you could generate a
SHAPE command by concatenating the command around the string returned by the Reshape Name property.
Reshape Name is a dynamic property appended to the Recordset object's Properties collection when the
CursorLocation property is set to adUseClient.
Applies To
Recordset Object (ADO )
See Also
Microsoft Data Shaping Service for OLE DB (ADO Service Provider)
Shape Commands in General
Recordset Object (ADO )
ExecuteOptionEnum
10/1/2018 • 2 minutes to read • Edit Online
adAsynchFetchNonBlocking has no
effect when the adCmdTableDirect
option is used to open the Recordset.
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.ExecuteOption.ASYNCEXECUTE
AdoEnums.ExecuteOption.ASYNCFETCH
AdoEnums.ExecuteOption.ASYNCFETCHNONBLOCKING
AdoEnums.ExecuteOption.NORECORDS
AdoEnums.ExecuteOption.UNSPECIFIED
Applies To
This example opens a Recordset on the Companies table of the Northwind database and then uses the Filter
property to limit the records visible to those where the CompanyName field starts with the letter D. Cut and paste
the following code to Notepad or another text editor, and save it as FilterJS.asp.
<html>
<head>
<title>ADO Recordset.Filter Example</title>
<style>
<!--
BODY {
font-family: 'Verdana','Arial','Helvetica',sans-serif;
BACKGROUND-COLOR:white;
COLOR:black;
}
.thead {
background-color: #008080;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
color: white;
}
.thead2 {
background-color: #800000;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
color: white;
}
.tbody {
text-align: center;
background-color: #f7efde;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
}
-->
</style>
</head>
<body bgcolor="White">
try
try
{
//open connection
Cnxn.Open(strCnxn);
rsCustomers.MoveFirst();
//set filter
filter = "CompanyName LIKE 'b*'";
rsCustomers.Filter = filter
if (rsCustomers.RecordCount == 0) {
Response.Write("No records matched ");
Response.Write (SQLCustomers + "So cannot make table...");
Cnxn.Close();
Response.End
}
else {
// show the data
Response.Write('<table width="100%" border="2">');
while(!rsCustomers.EOF) {
Response.Write('<tr class="tbody">');
for (var thisField = 0; thisField < rsCustomers.Fields.Count; thisField++) {
fld = rsCustomers(thisField);
fldValue = fld.Value;
if (fldValue == null)
fldValue = showNull;
if (fldValue == "")
thisField=showBlank;
Response.Write("<td>" + fldValue + "</td>")
}
rsCustomers.MoveNext();
Response.Write("</tr>");
}
// close the table
Response.Write("</table>");
}
}
catch (e)
{
Response.Write(e.message);
}
finally
{
// clean up
if (rsCustomers.State == adStateOpen)
rsCustomers.Close;
if (Cnxn.State == adStateOpen)
Cnxn.Close;
rsCustomers = null;
Cnxn = null;
}
%>
</body>
</html>
<!-- EndFilterJS -->
See Also
Filter Property
RecordCount Property (ADO )
Recordset Object (ADO )
Provider and DefaultDatabase Properties Example
(VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Provider property by opening three Connection objects using different providers.
It also uses the DefaultDatabase property to set the default database for the Microsoft ODBC Provider.
NOTE
If you are connecting to a data source provider that supports Windows authentication, you should specify
Trusted_Connection=yes or Integrated Security = SSPI instead of user ID and password information in the connection
string.
'BeginProviderVB
' clean up
Cnxn1.Close
Cnxn2.Close
Cnxn3.Close
Set Cnxn1 = Nothing
Set Cnxn2 = Nothing
Set Cnxn3 = Nothing
Exit Sub
ErrorHandler:
If Not Cnxn1 Is Nothing Then
If Cnxn1.State = adStateOpen Then Cnxn1.Close
End If
Set Cnxn1 = Nothing
End Sub
'EndProviderVB
See Also
Connection Object (ADO )
DefaultDatabase Property
Provider Property (ADO )
Open and Close Methods Example (VBScript)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Open and Close methods on both Recordset and Connection objects that have been
opened.
Use the following example in an Active Server Page (ASP ). Use Find to locate the file Adovbs.inc and place it in
the directory you plan to use. Cut and paste the following code into Notepad or another text editor, and save it as
OpenVBS.asp. You can view the result in any browser.
<BODY>
<H3>ADO Open Method</H3>
Cnxn.Open strCnxn
<HR>
<TR CLASS=thead2>
<TD>Product Name</TD>
<TD>Unit Price</TD>
</TR>
<!-- Display ADO Data Product List-->
<% Do Until rsProducts.EOF %>
<TR CLASS=tbody>
<TD> <%=rsProducts("ProductName")%> </TD>
<TD> <%=rsProducts("UnitPrice")%> </TD>
</TR>
<!-- Next Row = Record -->
<%rsProducts.MoveNext
Loop
' clean up
If rsProducts.State = adStateOpen then
rsProducts.Close
End If
If rsCustomers.State = adStateOpen then
rsCustomers.Close
End If
If Cnxn.State = adStateOpen then
Cnxn.Close
End If
Set rsProducts = Nothing
Set rsCustomers = Nothing
Set Cnxn = Nothing
%>
</TABLE>
</BODY>
</HTML>
<!-- EndOpenVBS -->
See Also
Close Method (ADO )
Connection Object (ADO )
Open Method (ADO Connection)
Open Method (ADO Recordset)
Recordset Object (ADO )
Open Method (ADO Connection)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
connection.Open ConnectionString, UserID, Password, Options
Parameters
ConnectionString
Optional. A String value that contains connection information. See the ConnectionString property for details
on valid settings.
UserID
Optional. A String value that contains a user name to use when establishing the connection.
Password
Optional. A String value that contains a password to use when establishing the connection.
Options
Optional. A ConnectOptionEnum value that determines whether this method should return after
(synchronously) or before (asynchronously) the connection is established.
Remarks
Using the Open method on a Connection object establishes the physical connection to a data source. After
this method successfully completes, the connection is live and you can issue commands against it and process
the results.
Use the optional ConnectionString argument to specify either a connection string containing a series of
argument = value statements separated by semicolons, or a file or directory resource identified with a URL.
The ConnectionString property automatically inherits the value used for the ConnectionString argument.
Therefore, you can either set the ConnectionString property of the Connection object before opening it, or
use the ConnectionString argument to set or override the current connection parameters during the Open
method call.
If you pass user and password information both in the ConnectionString argument and in the optional UserID
and Password arguments, the UserID and Password arguments will override the values specified in
ConnectionString.
When you have concluded your operations over an open Connection, use the Close method to free any
associated system resources. Closing an object does not remove it from memory; you can change its property
settings and use the Open method to open it again later. To completely eliminate an object from memory, set
the object variable to Nothing.
NOTE
Remote Data Service Usage When used on a client-side Connection object, the Open method doesn't actually
establish a connection to the server until a Recordset is opened on the Connection object.
NOTE
URLs using the http scheme will automatically invoke the Microsoft OLE DB Provider for Internet Publishing. For more
information, see Absolute and Relative URLs.
Applies To
Connection Object (ADO )
See Also
Open and Close Methods Example (VB )
Open and Close Methods Example (VBScript)
Open and Close Methods Example (VC++)
Open Method (ADO Record)
Open Method (ADO Recordset)
Open Method (ADO Stream)
OpenSchema Method
Optimize Property Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Field object's dynamic Optimize property. The zip field of the Authors table in the
Pubs database is not indexed. Setting the Optimize property to True on the zip field authorizes ADO to build an
index that improves the performance of the Find method.
'BeginOptimizeVB
Public Sub Main()
On Error GoTo ErrorHandler
ErrorHandler:
' clean up
If Not rstAuthors Is Nothing Then
If rstAuthors.State = adStateOpen Then rstAuthors.Close
End If
Set rstAuthors = Nothing
See Also
Field Object
Optimize Property-Dynamic (ADO )
ParentURL Property (ADO)
11/13/2018 • 2 minutes to read • Edit Online
Indicates an absolute URL string that points to the parent Record of the current Record object.
Return Value
Returns a String value that indicates the URL of the parent Record.
Remarks
The ParentURL property depends on the source used to open the Record object. For example, the Record can
be opened with a source that contains a relative path name of a directory referenced by the ActiveConnection
property.
Suppose "second" is a folder contained under "first". Open the Record object by using the following syntax:
record.ActiveConnection = "https://first"
record.Open "second"
Now, the value of the ParentURL property is "https://first" , the same as ActiveConnection.
The source can also be an absolute URL such as, "https://first/second" . The ParentURL property is then
"https://first" , the level above "second" .
NOTE
This property is only supported by document source providers, such as the Microsoft OLE DB Provider for Internet
Publishing. For more information, see Records and Provider-Supplied Fields.
NOTE
URLs using the http scheme will automatically invoke the Microsoft OLE DB Provider for Internet Publishing. For more
information, see Absolute and Relative URLs.
NOTE
If the current record contains a data record from an ADO Recordset, accessing the ParentURL property causes a run-time
error, indicating that no URL is possible.
Applies To
Record Object (ADO )
Clone Method Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Clone method to create copies of a Recordset and then lets the user position the record
pointer of each copy independently.
'BeginCloneVB
' Loop through the array so that on each pass the user
' is searching a different copy of the same Recordset
Do
For intLoop = 1 To 3
' Ask for search string while showing where
' the current record pointer is for each Recordset
strMessage = _
"Recordsets from stores table:" & vbCr & _
" 1 - Original - Record pointer at " & arstStores(1)!stor_name & vbCr & _
" 2 - Clone - Record pointer at " & arstStores(2)!stor_name & vbCr & _
" 3 - Clone - Record pointer at " & arstStores(3)!stor_name & vbCr & _
"Enter search string for #" & intLoop & ":"
strFind = Trim(InputBox(strMessage))
' make sure something was entered, if not then EXIT loop
If strFind = "" Then Exit Do
' clean up
arstStores(1).Close
arstStores(2).Close
arstStores(3).Close
Cnxn.Close
Set arstStores(1) = Nothing
Set arstStores(2) = Nothing
Set arstStores(3) = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not arstStores(1) Is Nothing Then
If arstStores(1).State = adStateOpen Then arstStores(1).Close
End If
Set arstStores(1) = Nothing
If Not arstStores(2) Is Nothing Then
If arstStores(2).State = adStateOpen Then arstStores(2).Close
End If
Set arstStores(2) = Nothing
If Not arstStores(3) Is Nothing Then
If arstStores(3).State = adStateOpen Then arstStores(3).Close
End If
Set arstStores(3) = Nothing
See Also
Clone Method (ADO )
Recordset Object (ADO )
Parameters Collection Properties, Methods, and
Events
10/1/2018 • 2 minutes to read • Edit Online
Properties
Count Property
Item Property
Methods
Append Method
Delete Method (ADO Parameters Collection)
Refresh Method
Events
None.
See Also
Parameters Collection (ADO )
MaxRecords Property Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the MaxRecords property to open a Recordset containing the 10 most expensive titles in the
Titles table.
'BeginMaxRecordsVB
Do Until rstTitles.EOF
Debug.Print " " & rstTitles!Title & " - " & rstTitles!Price
rstTitles.MoveNext
Loop
' clean up
rstTitles.Close
Cnxn.Close
Set rstTitles = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstTitles Is Nothing Then
If rstTitles.State = adStateOpen Then rstTitles.Close
End If
Set rstTitles = Nothing
See Also
MaxRecords Property (ADO )
Recordset Object (ADO )
ExecuteComplete Event (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
ExecuteComplete RecordsAffected, pError, adStatus, pCommand, pRecordset, pConnection
Parameters
RecordsAffected
A Long value indicating the number of records affected by the command.
pError
An Error object. It describes the error that occurred if the value of adStatus is adStatusErrorsOccurred;
otherwise it is not set.
adStatus
An EventStatusEnum status value. When this event is called, this parameter is set to adStatusOK if the operation
that caused the event was successful, or to adStatusErrorsOccurred if the operation failed.
Before this event returns, set this parameter to adStatusUnwantedEvent to prevent subsequent notifications.
pCommand
The Command object that was executed. Contains a Command object even when calling Connection.Execute
or Recordset.Open without explicitly creating a Command, in which cases the Command object is created
internally by ADO.
pRecordset
A Recordset object that is the result of the executed command. This Recordset may be empty. You should never
destroy this Recordset object from within this event handler. Doing so will result in an Access Violation when
ADO tries to access an object that no longer exists.
pConnection
A Connection object. The connection over which the operation was executed.
Remarks
An ExecuteComplete event may occur due to the Connection.Execute, Command.Execute, Recordset.Open,
Recordset.Requery, or Recordset.NextRecordset methods.
See Also
ADO Events Model Example (VC++)
ADO Event Handler Summary
CopyRecord, CopyTo, and SaveToFile Methods
Example (VB)
11/13/2018 • 2 minutes to read • Edit Online
This example demonstrates how to create copies of a file using Stream or Record objects. One copy is made to a
Web folder for Internet publishing. Other properties and methods shown include Stream Type, Open,
LoadFromFile, and Record Open.
'BeginCopyRecordVB
'Note:
' This sample requires that "C:\checkmrk.wmf" and
' "https://MyServer/mywmf.wmf" exist.
Option Explicit
' Load each copy of the graphic into Image controls for viewing
Image1.Picture = LoadPicture(strPicturePath)
Image2.Picture = LoadPicture(strStreamPath)
Image3.Picture = LoadPicture(strStream2Path)
Image4.Picture = LoadPicture(strRecordPath)
' clean up
objStream.Close
objStream2.Close
objRecord.Close
Set objStream = Nothing
Set objStream2 = Nothing
Set objRecord = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not objStream Is Nothing Then
If objStream.State = adStateOpen Then objStream.Close
End If
Set objStream = Nothing
See Also
CopyRecord Method (ADO )
CopyTo Method (ADO )
LoadFromFile Method (ADO )
Open Method (ADO Record)
Open Method (ADO Stream)
Record Object (ADO )
SaveToFile Method
Stream Object (ADO )
Type Property (ADO Stream)
Errors Collection Properties, Methods, and Events
10/1/2018 • 2 minutes to read • Edit Online
Properties
Count Property
Item Property
Methods
Clear Method
Refresh Method
Events
None.
See Also
Errors Collection (ADO )
ParentRow Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Sets the container of an OLE DB Row object on an ADORecordConstruction object, so that the parent of the row
is turned into an ADO Record object.
Write-only.
Syntax
HRESULT put_ParentRow([in] IUnknown* pParent);
Parameters
pParent
A container of a row.
Return Values
This property method returns the standard HRESULT values, including S_OK and E_FAIL.
Applies To
ADORecordConstruction Interface
Description, HelpContext, HelpFile, NativeError,
Number, Source, and SQLState Properties Example
(VB)
10/1/2018 • 2 minutes to read • Edit Online
This example triggers an error, traps it, and displays the Description, HelpContext, HelpFile, NativeError, Number,
Source, and SQLState properties of the resulting Error object.
'BeginDescriptionVB
Public Sub Main()
ErrorHandler:
Debug.Print strError
Next
Resume Next
End Sub
'EndDescriptionVB
See Also
Description Property
Error Object
HelpContext, HelpFile Properties
HelpContext, HelpFile Properties
NativeError Property (ADO )
Number Property (ADO )
Source Property (ADO Error)
SQLState Property
Cancel Method Example (VB)
11/28/2018 • 2 minutes to read • Edit Online
This example uses the Cancel method to cancel a command executing on a Connection object if the connection is
busy.
'BeginCancelVB
' If the command has NOT completed, cancel the execute and
' roll back the transaction; otherwise, commit the transaction
If CBool(Cnxn.State And adStateExecuting) Then
Cnxn.Cancel
Cnxn.RollbackTrans
blnChanged = False
MsgBox "Update canceled."
Else
Cnxn.CommitTrans
blnChanged = True
MsgBox "Update complete."
End If
' clean up
Cnxn.Close
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
If Not Cnxn Is Nothing Then
If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing
See Also
Cancel Method (ADO )
Connection Object (ADO )
AbsolutePage, PageCount, and PageSize Properties
Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
'BeginAbsolutePageVB
'Open connection
Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn
' clean up
rstEmployees.Close
Cnxn.Close
Set rstEmployees = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
ErrorHandler:
' clean up
If Not rstEmployees Is Nothing Then
If rstEmployees.State = adStateOpen Then rstEmployees.Close
End If
Set rstEmployees = Nothing
See Also
AbsolutePage Property (ADO )
PageCount Property (ADO )
PageSize Property (ADO )
Recordset Object (ADO )
GetDataProviderDSO Method
10/1/2018 • 2 minutes to read • Edit Online
Retrieves the underlying OLE DB Data Source object from the Shape provider.
Syntax
HRESULT GetDataProviderDSO(
IUnknown **ppDataProviderDSOIUnknown
);
Parameters
ppDataProviderDSOIUnknown
[out] A pointer to a pointer that returns the IUnknown of the underlying OLE DB Data Source object.
Remarks
This method does not addref the interface pointer. If the caller plans to hold the pointer, the caller must do the
required addref and release.
Applies to
IDSOShapeExtensions Interface
Find Method Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Recordset object's Find method to locate and count the number of business titles in the
Pubs database. The example assumes the underlying provider does not support similar functionality.
// BeginFindCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
#include "icrsint.h"
// Column title_id is the first field in the recordset from Titles table.
ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, m_szt_titleid, sizeof(m_szt_titleid), lt_titleidStatus, FALSE)
END_ADO_BINDING()
public:
CHAR m_szt_titleid[150];
ULONG lt_titleidStatus;
};
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void FindX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
FindX();
::CoUninitialize();
}
void FindX() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
_RecordsetPtr pRstTitles = NULL;
IADORecordBinding *picRs = NULL; // Interface Pointer declared.
CTitlesRs titlers; // C++ class object
try {
// Open connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open (strCnn, "", "", adConnectUnspecified);
// Skip the current record to avoid finding the same row repeatedly.
// The bookmark is redundant because Find searches from the current position.
int count = 0;
if (pRstTitles)
if (pRstTitles->State == adStateOpen)
pRstTitles->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}
if ( (pConnection->Errors->Count) > 0 ) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number, (LPCSTR)pErr->Description);
}
}
}
See Also
Find Method (ADO )
Recordset Object (ADO )
SaveOptionsEnum
10/1/2018 • 2 minutes to read • Edit Online
Specifies whether a file should be created or overwritten when saving from a Stream object. The values can be
adSaveCreateNotExist or adSaveCreateOverWrite..
ADO/WFC Equivalent
These constants do not have ADO/WFC equivalents.
Applies To
SaveToFile Method
ADO for Visual C++ Syntax Index with #import
10/1/2018 • 2 minutes to read • Edit Online
This index is a cross-reference to the ADO Language Reference based on Microsoft Visual C++ and the #import
directive.
This particular index was derived by compiling a program with the #import directive against the ADO .dll, then
reformatting the *.tlh file that was generated. Only information about methods, properties, and events was
preserved. The alternative syntax declared for each property is listed by the corresponding "
__declspec(property...) " directive.
You are strongly encouraged to read Visual C++ ADO Programming for more information.
Method and property syntax in Visual C++ with the #import directive is listed for the following elements:
ADO Collections
Command Object
Connection Object
Error Object
Field Object
Parameter Object
Property object
Record Object
Recordset Object
Stream Object
Connection Events
Recordset Events
See Also
ADO for Visual C++ Syntax Index for COM
Sort Property Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Recordset object's Sort property to reorder the rows of a Recordset derived from the
Authors table of the Pubs database. A secondary utility routine prints each row.
// SortPropertyExample.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void SortX();
void SortXprint(_bstr_t title, _RecordsetPtr rstp);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
SortX();
::CoUninitialize();
}
void SortX() {
// Initialize pointers on define. These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
_RecordsetPtr pRstAuthors = NULL;
try {
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
pRstAuthors->CursorLocation = adUseClient;
pConnection->Open (strCnn, "", "", adConnectUnspecified);
pRstAuthors->Open("SELECT * FROM authors",
_variant_t((IDispatch *) pConnection),
adOpenStatic, adLockReadOnly, adCmdText);
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
Recordset Object (ADO )
Sort Property
EOS Property
10/1/2018 • 2 minutes to read • Edit Online
Return Values
Returns a Boolean value that indicates whether the current position is at the end of the stream. EOS returns
True if there are no more bytes in the stream; it returns False if there are more bytes following the current
position.
To set the end of stream position, use the SetEOS method. To determine the current position, use the Position
property.
Applies To
Stream Object (ADO )
See Also
EOS and LineSeparator Properties and SkipLine Method Example (VB )
Stream Object (ADO )
Seek Method and Index Property Example (VC++)
10/1/2018 • 3 minutes to read • Edit Online
This example uses the Recordset object's Seek method and Index property in conjunction with a given Employee
ID, to locate the employee's name in the Employees table of the Nwind.mdb database.
// BeginSeekCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <stdio.h>
#include <ole2.h>
#include <conio.h>
#include <string.h>
#include "icrsint.h"
public:
INT m_ie_empid;
ULONG le_empidStatus;
CHAR m_sze_fname[11];
ULONG le_fnameStatus;
CHAR m_sze_lname[21];
ULONG le_lnameStatus;
};
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void SeekX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
if (pstrRet == NULL)
return NULL;
if (!strrchr(strDest, '\n'))
// Exhaust the input buffer.
do {
fgets(strExBuff, sizeof(strExBuff), stdin);
} while (!strrchr(strExBuff, '\n'));
else
// Replace '\n' with '\0'
// Replace '\n' with '\0'
strDest[strrchr(strDest, '\n') - strDest] = '\0';
return pstrRet;
}
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
SeekX();
::CoUninitialize();
}
void SeekX() {
HRESULT hr = S_OK;
// Define ADO object pointers, initialize pointers on define. These are in the ADODB:: namespace.
_RecordsetPtr pRstEmp = NULL;
try {
TESTHR(pRstEmp.CreateInstance(__uuidof(Recordset)));
pRstEmp->CursorLocation = adUseServer;
pRstEmp->Open("employees", "Provider='Microsoft.Jet.OLEDB.4.0';"
"Data Source='C:\\Program Files\\Microsoft Office\\Office\\"
"Samples\\Northwind.mdb';",
adOpenKeyset,adLockReadOnly,adCmdTableDirect);
pRstEmp->MoveNext();
}
// Prompt the user for an EmployeeID between 1 and 9.
do {
pRstEmp->MoveFirst();
printf("\n\n%s\t",(LPCSTR) strPrompt);
mygets(strEmpId, 2);
if (pRstEmp)
if (pRstEmp->State == adStateOpen)
pRstEmp->Close();
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
See Also
Index Property
Recordset Object (ADO )
Seek Method
ConnectComplete and Disconnect Events (ADO)
10/1/2018 • 2 minutes to read • Edit Online
The ConnectComplete event is called after a connection starts. The Disconnect event is called after a
connection ends.
Syntax
ConnectComplete pError, adStatus, pConnection
Disconnect adStatus, pConnection
Parameters
pError
An Error object. It describes the error that occurred if the value of adStatus is adStatusErrorsOccurred;
otherwise it is not set.
adStatus
An EventStatusEnum value that always returns adStatusOK.
When ConnectComplete is called, this parameter is set to adStatusCancel if a WillConnect event has
requested cancellation of the pending connection.
Before either event returns, set this parameter to adStatusUnwantedEvent to prevent subsequent notifications.
However, closing and reopening the Connection causes these events to occur again.
pConnection
The Connection object for which this event applies.
See Also
ADO Events Model Example (VC++)
ADO Event Handler Summary
Move Method Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Move method to position the record pointer based on user input.
'BeginMoveVB
rstAuthors.MoveFirst
Do
' Display information about current record and
' ask how many records to move
strCommand = InputBox( _
"Record " & rstAuthors.AbsolutePosition & _
" of " & rstAuthors.RecordCount & vbCr & _
"Author: " & rstAuthors!au_fname & _
" " & rstAuthors!au_lname & vbCr & _
"Location: " & rstAuthors!city & _
", " & rstAuthors!State & vbCr & vbCr & _
"Enter number of records to Move " & _
"(positive or negative).")
lngMove = CLng(Val(strCommand))
If lngMove = 0 Then
MsgBox "You either entered a non-number or canceled the input box. Exit the application."
Exit Do
End If
' clean up
rstAuthors.Close
Cnxn.Close
Set rstAuthors = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstAuthors Is Nothing Then
If rstAuthors.State = adStateOpen Then rstAuthors.Close
End If
Set rstAuthors = Nothing
See Also
Move Method (ADO )
Recordset Object (ADO )
NumericScale and Precision Properties Example
(VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the NumericScale and Precision properties to display the numeric scale and precision of fields
in the Discounts table of the Pubs database.
// BeginNumericScaleCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void NumericScaleX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
NumericScaleX();
::CoUninitialize();
}
void NumericScaleX() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace
_RecordsetPtr pRstDiscounts = NULL;
FieldsPtr fldTemp = NULL;
try {
// Open recordset.
TESTHR(pRstDiscounts.CreateInstance(__uuidof(Recordset)));
pRstDiscounts->Open("discounts", strCnn, adOpenForwardOnly, adLockReadOnly, adCmdTable);
// Display numeric scale and precision of numeric and small integer fields.
fldTemp = pRstDiscounts->GetFields();
if ( (fldTemp->GetItem(Index)->Type == adNumeric) ||
(fldTemp->GetItem(Index)->Type == adSmallInt) ) {
printf("Field: %s\n" , (LPCSTR)fldTemp->GetItem(Index)->GetName());
printf("Numeric scale: %d\n", fldTemp->GetItem(Index)->GetNumericScale());
printf("Precision: %d\n", fldTemp->GetItem(Index)->GetPrecision());
}
}
}
}
catch(_com_error &e) {
// Display errors, if any. Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstDiscounts->GetActiveConnection();
if ( (pConnection->Errors->Count) > 0 ) {
long nCount = pConnection->Errors->Count;
See Also
NumericScale Property (ADO )
Precision Property (ADO )
BookmarkEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.Bookmark.CURRENT
AdoEnums.Bookmark.FIRST
AdoEnums.Bookmark.LAST
Applies To
Searches a Recordset for the row that satisfies the specified criteria. Optionally, the direction of the search,
starting row, and offset from the starting row may be specified. If the criteria is met, the current row position is
set on the found record; otherwise, the position is set to the end (or start) of the Recordset.
Syntax
Find (Criteria, SkipRows, SearchDirection, Start)
Parameters
Criteria
A String value that contains a statement specifying the column name, comparison operator, and value to use in
the search.
SkipRows
Optional*.* A Long value, whose default value is zero, that specifies the row offset from the current row or
Start bookmark to begin the search. By default, the search will start on the current row.
SearchDirection
Optional*.* A SearchDirectionEnum value that specifies whether the search should begin on the current row or
the next available row in the direction of the search. An unsuccessful search stops at the end of the Recordset if
the value is adSearchForward. An unsuccessful search stops at the start of the Recordset if the value is
adSearchBackward.
Start
Optional. A Variant bookmark that functions as the starting position for the search.
Remarks
Only a single-column name may be specified in criteria. This method does not support multi-column searches.
The comparison operator in Criteria may be ">" (greater than), "<" (less than), "=" (equal), ">=" (greater than or
equal), "<=" (less than or equal), "<>" (not equal), or "like" (pattern matching).
The value in Criteria may be a string, floating-point number, or date. String values are delimited with single
quotes or "#" (number sign) marks (for example, "state = 'WA'" or "state = #WA#"). Date values are delimited
with "#" (number sign) marks (for example, "start_date > #7/22/97#"). These values can contain hours, minutes,
and seconds to indicate time stamps, but should not contain milliseconds or errors will occur.
If the comparison operator is "like", the string value may contain an asterisk (*) to find one or more occurrences
of any character or substring. For example, "state like 'M*'" matches Maine and Massachusetts. You can also use
leading and trailing asterisks to find a substring contained within the values. For example, "state like '*as*'"
matches Alaska, Arkansas, and Massachusetts.
Asterisks can be used only at the end of a criteria string, or at both the beginning and end of a criteria string, as
shown above. You cannot use the asterisk as a leading wildcard ('*str'), or as an embedded wildcard ('s*r'). This
will cause an error.
NOTE
An error will occur if a current row position is not set before calling Find. Any method that sets row position, such as
MoveFirst, should be called before calling Find.
NOTE
If you call the Find method on a recordset, and the current position in the recordset is at the last record or end of file
(EOF), you will not find anything. You need to call the MoveFirst method to set the current position/cursor to the
beginning of the recordset.
Applies To
Recordset Object (ADO )
See Also
Find Method Example (VB )
Index Property
Optimize Property-Dynamic (ADO )
Seek Method
Update and CancelUpdate Methods Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Update method in conjunction with the CancelUpdate method.
'BeginUpdateVB
Public Sub Main()
On Error GoTo ErrorHandler
' clean up
rstEmployees.Close
Cnxn.Close
Set rstEmployees = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstEmployees Is Nothing Then
If rstEmployees.State = adStateOpen Then rstEmployees.Close
End If
Set rstEmployees = Nothing
This example demonstrates the Update method in conjunction with the AddNew method.
See Also
CancelUpdate Method (ADO )
Recordset Object (ADO )
Update Method
Count Property Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Count property with two collections in the Employee database. The property
obtains the number of objects in each collection, and sets the upper limit for loops that enumerate these
collections.
// BeginCountCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include<conio.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void CountX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
CountX();
::CoUninitialize();
}
void CountX() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace
_RecordsetPtr pRstEmployee = NULL;
try {
// Open recordset with data from Employee table.
TESTHR(pRstEmployee.CreateInstance(__uuidof(Recordset)));
pRstEmployee->Open("Employee", strCnn, adOpenForwardOnly, adLockReadOnly, adCmdTable);
switch(vtConnect.vt) {
case VT_BSTR:
PrintComError(e);
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}
// Clean up objects before exit.
if (pRstEmployee)
if (pRstEmployee->State == adStateOpen)
pRstEmployee->Close();
}
if ( (pConnection->Errors->Count) > 0 ) {
long nCount = pConnection->Errors->Count;
See Also
Count Property (ADO )
Parameter Object Properties, Methods, and Events
10/1/2018 • 2 minutes to read • Edit Online
Properties/Collections
Attributes Property
Direction Property
Name Property
NumericScale Property
Precision Property
Properties Collection
Size Property
Type Property
Value Property
Methods
AppendChunk Method
Events
None.
See Also
Parameter Object
Description, HelpContext, HelpFile, NativeError,
Number, Source, and SQLState Properties Example
(VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example triggers an error, traps it, and displays the Description, HelpContext, HelpFile, NativeError, Number,
Source, and SQLState properties of the resulting Error object.
// BeginDescriptionCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
// Function declarations
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void DescriptionX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
DescriptionX();
::CoUninitialize();
}
void DescriptionX() {
// Define ADO object pointers. Initialize pointers on define. These are in the ADODB:: namespace
_ConnectionPtr pConnection = NULL;
ErrorPtr errorLoop = NULL;
try {
// Intentionally trigger an error. open connection
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
try {
// Enumerate Errors collection and display properties of each Error object.
long nCount = pConnection->Errors->Count;
if ((LPCSTR)pErr->GetHelpFile() == NULL)
printf("\tNo Help file available\n");
else {
printf("\t(HelpFile: %s\n)" ,pErr->HelpFile);
printf("\t(HelpContext: %s\n)" , pErr->HelpContext);
}
}
}
catch(_com_error &e) {
// Notify the user of errors if any.
PrintComError(e);
}
}
See Also
Description Property
Error Object
HelpContext, HelpFile Properties
HelpContext, HelpFile Properties
NativeError Property (ADO )
Number Property (ADO )
Source Property (ADO Error)
SQLState Property
ActiveConnection Property (ADO)
10/1/2018 • 3 minutes to read • Edit Online
Indicates to which Connection object the specified Command, Recordset, or Record object currently belongs.
Remarks
Use the ActiveConnection property to determine the Connection object over which the specified
Command object will execute or the specified Recordset will be opened.
Command
For Command objects, the ActiveConnection property is read/write.
If you attempt to call the Execute method on a Command object before setting this property to an open
Connection object or valid connection string, an error occurs.
If a Connection object is assigned to the ActiveConnection property, the object must be opened. Assigning
a closed Connection object causes an error.
Note
Microsoft Visual Basic Setting the ActiveConnection property to Nothing disassociates the Command
object from the current Connection and causes the provider to release any associated resources on the data
source. You can then associate the Command object with the same or another Connection object. Some
providers allow you to change the property setting from one Connection to another, without having to first
set the property to Nothing.
If the Parameters collection of the Command object contains parameters supplied by the provider, the
collection is cleared if you set the ActiveConnection property to Nothing or to another Connection object. If
you manually create Parameter objects and use them to fill the Parameters collection of the Command
object, setting the ActiveConnection property to Nothing or to another Connection object leaves the
Parameters collection intact.
Closing the Connection object with which a Command object is associated sets the ActiveConnection
property to Nothing. Setting this property to a closed Connection object generates an error.
Recordset
For open Recordset objects or for Recordset objects whose Source property is set to a valid Command
object, the ActiveConnection property is read-only. Otherwise, it is read/write.
You can set this property to a valid Connection object or to a valid connection string. In this case, the provider
creates a new Connection object using this definition and opens the connection. Additionally, the provider
may set this property to the new Connection object to give you a way to access the Connection object for
extended error information or to execute other commands.
If you use the ActiveConnection argument of the Open method to open a Recordset object, the
ActiveConnection property will inherit the value of the argument.
If you set the Source property of the Recordset object to a valid Command object variable, the
ActiveConnection property of the Recordset inherits the setting of the Command object's
ActiveConnection property.
NOTE
Remote Data Service Usage When used on a client-side Recordset object, this property can be set only to a
connection string or (in Microsoft Visual Basic or Visual Basic, Scripting Edition) to Nothing.
Record
This property is read/write when the Record object is closed, and may contain a connection string or reference
to an open Connection object. This property is read-only when the Record object is open, and contains a
reference to an open Connection object.
A Connection object is created implicitly when the Record object is opened from a URL. Open the Record
with an existing, open Connection object by assigning the Connection object to this property, or using the
Connection object as a parameter in the Open method call. If the Record is opened from an existing Record
or Recordset, then it is automatically associated with that Record or Recordset object's Connection object.
NOTE
URLs using the http scheme will automatically invoke the Microsoft OLE DB Provider for Internet Publishing. For more
information, see Absolute and Relative URLs.
Applies To
See Also
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(VB )
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(VC++)
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(JScript)
Connection Object (ADO )
ConnectionString Property (ADO )
ADORecordConstruction Interface
10/1/2018 • 2 minutes to read • Edit Online
The ADORecordConstructioninterface is used to construct an ADO Record object from an OLE DB Row object
in a C/C++ application.
This interface supports the following properties:
Properties
ParentRow Write-only.
Sets the container of an OLE DB Row object on this ADO
Record object.
Row Read/Write.
Gets/sets an OLE DB Row object from/on this ADO Record
object.
Methods
None.
Events
None.
Remarks
Given an OLE DB Row object ( pRow ), the construction of an ADO Record object ( adoR ), amounts to the
following three basic operations:
1. Create an ADO Record object:
_RecordPtr adoR;
adoRs.CreateInstance(__uuidof(_Record));
adoRecordConstructionPtr adoRConstruct=NULL;
adoR->QueryInterface(__uuidof(ADORecordConstruction),
(void**)&adoRConstruct);
3. Call the IADORecordConstruction::put_Row property method to set the OLE DB Row object on the
ADO Record object:
IUnknown *pUnk=NULL;
pRow->QueryInterface(IID_IUnknown, (void**)&pUnk);
adoRConstruct->put_Row(pUnk);
The resultant adoR object now represents the ADO Record object constructed from the OLE DB Row object.
An ADO Record object can also be constructed from the container of an OLE DB Row object.
Requirements
Version: ADO 2.0 and later
Library: msado15.dll
UUID: 00000567-0000-0010-8000-00AA006D2EA4
AppendChunk and GetChunk Methods Example
(VC++)
10/1/2018 • 3 minutes to read • Edit Online
This example uses the AppendChunk and GetChunk methods to fill an image field with data from another record.
// BeginAppendChunkCpp.cpp
// compile with: /EHsc /c
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include "conio.h"
#include "malloc.h"
#include "icrsint.h"
public:
CHAR m_sz_pubid[10];
ULONG l_pubid;
CHAR m_sz_prinfo[200];
ULONG l_prinfo;
};
//Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void AppendChunkX();
void PrintProviderError(_ConnectionPtr pConnection);
if (pstrRet == NULL)
return 0;
if (!strrchr(strDest, '\n'))
// Exhaust the input buffer.
do {
fgets(strExBuff, sizeof(strExBuff), stdin);
} while (!strrchr(strExBuff, '\n'));
else
// Replace '\n' with '\0'
strDest[strrchr(strDest, '\n') - strDest] = '\0';
return strlen(strDest);
}
inline char* mygets(char* strDest, int n) {
char strExBuff[10];
char* pstrRet = fgets(strDest, n, stdin);
if (pstrRet == NULL)
return NULL;
return NULL;
if (!strrchr(strDest, '\n'))
// Exhaust the input buffer.
do {
fgets(strExBuff, sizeof(strExBuff), stdin);
} while (!strrchr(strExBuff, '\n'));
else
// Replace '\n' with '\0'
strDest[strrchr(strDest, '\n') - strDest] = '\0';
return pstrRet;
}
int main() {
HRESULT hr = S_OK;
if (FAILED(::CoInitialize(NULL)))
return -1;
AppendChunkX();
::CoUninitialize();
}
void AppendChunkX() {
// Define ADO object pointers, initialize pointers on define. These are in the ADODB:: namespace.
_RecordsetPtr pRstPubInfo = NULL;
_ConnectionPtr pConnection = NULL;
char * token1;
HRESULT hr = S_OK;
_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");
_bstr_t strMessage,strPubID,strPRInfo;
_variant_t varChunk;
long lngOffSet,lngLogoSize;
char pubId[50];
lngOffSet = 0;
UCHAR chData;
SAFEARRAY FAR *psa;
SAFEARRAYBOUND rgsabound[1];
rgsabound[0].lLbound = 0;
rgsabound[0].cElements = ChunkSize;
try {
// Open a Connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
hr = pConnection->Open(strCnn, "", "", adConnectUnspecified);
TESTHR(hr= pRstPubInfo.CreateInstance(__uuidof(Recordset)));
pRstPubInfo->CursorType = adOpenKeyset;
pRstPubInfo->LockType = adLockOptimistic;
hr = pRstPubInfo->Open("pub_info", _variant_t((IDispatch*)pConnection,true),
adOpenKeyset, adLockOptimistic, adCmdTable);
long index1 = 0;
while (lngOffSet < lngLogoSize) {
varChunk = pRstPubInfo->Fields->Item["logo"]->GetChunk(ChunkSize);
pRstPubInfo->AddNew();
pRstPubInfo->Fields->GetItem("pub_id")->PutValue(strPubID);
pRstPubInfo->Fields->GetItem("pr_info")->PutValue(pubrs.m_sz_prinfo);
lngLogoSize = pRstPubInfo->Fields->Item["logo"]->ActualSize;
// Show the newly added record.
printf("New Record : %s\n Description : %s\n Logo Size : %s",
pubrs.m_sz_pubid,
pubrs.m_sz_prinfo,(LPCSTR)(_bstr_t)pRstPubInfo->Fields->
Item["logo"]->ActualSize);
PrintProviderError(pConnection);
printf("Source : %s \n Description : %s\n", (LPCSTR)bstrSource,
(LPCSTR)bstrDescription);
}
if ( (pConnection->Errors->Count) > 0) {
nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for (i = 0 ; i < nCount ; i++) {
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
AppendChunk Method (ADO )
Field Object
GetChunk Method (ADO )
Execute, Requery, and Clear Methods Example
(JScript)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Execute method when run from both a Command object and a Connection object.
It also uses the Requery method to retrieve current data in a Recordset, and the Clear method to clear the contents
of the Errors collection. (The Errors collection is accessed via the Connection object of the ActiveConnection
property of the Recordset.) Name the file ExecuteJS.asp.
<%
strLastName = new String(Request.Form("AuthorLName"));
<html>
<head>
<title>Execute, Requery and Clear Methods Example (JScript)</title>
<style>
<!--
BODY {
font-family: 'Verdana','Arial','Helvetica',sans-serif;
BACKGROUND-COLOR:white;
COLOR:black;
}
-->
</style>
</head>
<body bgcolor="White">
<h1>Execute, Requery and Clear Methods Example (JScript)</h1>
<%
if (strLastName.length > 0)
{
// command and recordset variables
var Connect = "Provider='sqloledb';Data Source=" + Request.ServerVariables("SERVER_NAME") + ";" +
"Initial Catalog='pubs';Integrated Security='SSPI';";
var Cnxn = Server.CreateObject("ADODB.Connection");
var cmdAuthor = Server.CreateObject("ADODB.Command");
var rsAuthor = Server.CreateObject("ADODB.Recordset");
var rsAuthor2 = Server.CreateObject("ADODB.Recordset");
var SQLAuthor2, strMessage, strMessage2;
var Err, ErrCount;
try
{
// open connection
Cnxn.Open(Connect);
// first recordset
Response.Write("<b>Command.Execute results</b>")
while (!rsAuthor.EOF)
{
// build output string by starting a new line
strMessage = "<P>";
strMessage += "<br>";
// recordset data
strMessage += rsAuthor("au_fname") + " ";
strMessage += rsAuthor("au_lname") + " ";
Response.Write("<HR><HR>");
// second recordset
Response.Write("<b>Connection.Execute results</b>")
while (!rsAuthor2.EOF)
{
// start a new line
strMessage2 = "<P>";
// show results
Response.Write(strMessage2);
<hr>
</html>
<!-- EndExecuteJS -->
See Also
Clear Method (ADO )
Command Object (ADO )
Connection Object (ADO )
Error Object
Execute Method (ADO Command)
Execute Method (ADO Connection)
Recordset Object (ADO )
Requery Method
RecordStatusEnum
10/1/2018 • 2 minutes to read • Edit Online
Specifies the status of a record with regard to batch updates and other bulk operations.
ADO/WFC Equivalent
AdoEnums.RecordStatus.
Package: com.ms.wfc.data
CONSTANT
AdoEnums.RecordStatus.CANCELED
AdoEnums.RecordStatus.CANTRELEASE
AdoEnums.RecordStatus.CONCURRENCYVIOLATION
AdoEnums.RecordStatus.DBDELETED
AdoEnums.RecordStatus.DELETED
AdoEnums.RecordStatus.INTEGRITYVIOLATION
AdoEnums.RecordStatus.INVALID
AdoEnums.RecordStatus.MAXCHANGESEXCEEDED
AdoEnums.RecordStatus.MODIFIED
AdoEnums.RecordStatus.MULTIPLECHANGES
AdoEnums.RecordStatus.NEW
AdoEnums.RecordStatus.OBJECTOPEN
AdoEnums.RecordStatus.OK
AdoEnums.RecordStatus.OUTOFMEMORY
AdoEnums.RecordStatus.PENDINGCHANGES
CONSTANT
AdoEnums.RecordStatus.PERMISSIONDENIED
AdoEnums.RecordStatus.SCHEMAVIOLATION
AdoEnums.RecordStatus.UNMODIFIED
Applies To
Status Property (ADO Recordset)
StayInSync Property
10/1/2018 • 2 minutes to read • Edit Online
Indicates, in a hierarchical Recordset object, whether the reference to the underlying child records (that is, the
chapter) changes when the parent row position changes.
Remarks
This property applies to hierarchical recordsets, such as those supported by the Microsoft Data Shaping Service
for OLE DB, and must be set on the parent Recordset before the child Recordset is retrieved. This property
simplifies navigating hierarchical recordsets.
Applies To
Recordset Object (ADO )
See Also
StayInSync Property Example (VB )
Microsoft Data Shaping Service for OLE DB (ADO Service Provider)
Resync Command Property-Dynamic (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Specifies a user-supplied command string that the Resync method issues to refresh the data in the table named in
the Unique Table dynamic property.
Remarks
The Recordset object is the result of a JOIN operation executed on multiple base tables. The rows affected depend
on the AffectRecords parameter of the Resync method. The standard Resync method is executed if the Unique
Table and Resync Command properties are not set.
The command string of the Resync Command property is a parameterized command or stored procedure that
uniquely identifies the row being refreshed, and returns a single row containing the same number and order of
columns as the row to be refreshed. The command string contains a parameter for each primary key column in
the Unique Table; otherwise, a run-time error is returned. The parameters are automatically filled in with primary
key values from the row to be refreshed.
Here are two examples based on SQL:
1) The Recordset is defined by a command:
"SELECT * FROM
(SELECT * FROM Customers JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
city = 'Seattle' ORDER BY CustomerID)
WHERE Orders.OrderID = ?"
The Unique Table is Orders and its primary key, OrderID, is parameterized. The sub-select provides a simple way
to programmatically ensure that the same number and order of columns are returned as by the original
command.
2) The Recordset is defined by a stored procedure:
Once again, the Unique Table is Orders and its primary key, OrderID, is parameterized.
Resync Command is a dynamic property appended to the Recordset object Properties collection when the
CursorLocation property is set to adUseClient.
Applies To
Recordset Object (ADO )
CursorOptionEnum
10/1/2018 • 2 minutes to read • Edit Online
CONSTANT
AdoEnums.CursorOption.ADDNEW
AdoEnums.CursorOption.APPROXPOSITION
AdoEnums.CursorOption.BOOKMARK
AdoEnums.CursorOption.DELETE
AdoEnums.CursorOption.FIND
AdoEnums.CursorOption.HOLDRECORDS
AdoEnums.CursorOption.INDEX
AdoEnums.CursorOption.MOVEPREVIOUS
AdoEnums.CursorOption.NOTIFY
AdoEnums.CursorOption.RESYNC
AdoEnums.CursorOption.SEEK
AdoEnums.CursorOption.UPDATE
AdoEnums.CursorOption.UPDATEBATCH
Applies To
Supports Method
ConnectionString, ConnectionTimeout, and State
Properties Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates different ways of using the ConnectionString property to open a Connection object. It
also uses the ConnectionTimeout property to set a connection timeout period, and the State property to check the
state of the connections. The GetState function is required for this procedure to run.
NOTE
If you are connecting to a data source provider that supports Windows authentication, you should specify
Trusted_Connection=yes or Integrated Security = SSPI instead of user ID and password information in the connection
string.
'BeginConnectionStringVB
' clean up
Cnxn1.Close
Cnxn2.Close
Cnxn3.Close
Cnxn4.Close
Set Cnxn1 = Nothing
Set Cnxn2 = Nothing
Set Cnxn3 = Nothing
Set Cnxn4 = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not Cnxn1 Is Nothing Then
If Cnxn1.State = adStateOpen Then Cnxn1.Close
End If
Set Cnxn1 = Nothing
End Function
'EndConnectionStringVB
See Also
Connection Object (ADO )
ConnectionString Property (ADO )
ConnectionTimeout Property (ADO )
State Property (ADO )
CommandText Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the CommandText property to set or return the text of a command represented by a Command object.
Usually this will be an SQL statement, but can also be any other type of command statement recognized by
the provider, such as a stored procedure call. An SQL statement must be of the particular dialect or version
supported by the provider's query processor.
If the Prepared property of the Command object is set to True and the Command object is bound to an
open connection when you set the CommandText property, ADO prepares the query (that is, a compiled
form of the query that is stored by the provider) when you call the Execute or Open methods.
Depending on the CommandType property setting, ADO may alter the CommandText property. You can
read the CommandText property at any time to see the actual command text that ADO will use during
execution.
Use the CommandText property to set or return a relative URL that specifies a resource, such as a file or
directory. The resource is relative to a location specified explicitly by an absolute URL, or implicitly by an open
Connection object.
NOTE
URLs using the http scheme will automatically invoke the Microsoft OLE DB Provider for Internet Publishing. For more
information, see Absolute and Relative URLs.
Applies To
Command Object (ADO )
See Also
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(VB )
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(VC++)
Requery Method
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example
(JScript)
GetString Method Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
Example
// BeginGetString.cpp
// compile with: /EHsc /c
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
// Function declarations
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void GetStringX(void);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
if (pstrRet == NULL)
return NULL;
return pstrRet;
}
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
GetStringX();
::CoUninitialize();
}
void GetStringX() {
HRESULT hr = S_OK;
char * token1;
try {
// Open connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
printf("%s",strPrompt);
mygets(strState, 3);
char strQry[100];
_snprintf_s(strQry, _countof(strQry), sizeof(strQry)-1, "SELECT au_fname, au_lname, address, city "
"FROM authors WHERE state = '%s'", pState);
strQry[sizeof(strQry)-1] = '\0';
if (pRstAuthors->RecordCount > 0) {
// Use all defaults: get all rows, TAB column delimiter,
// CARRIAGE RETURN row delimiter, empty-string null delimiter
long lRecCount = pRstAuthors->RecordCount;
_bstr_t varTab("\t");
_bstr_t varRet("\r");
_bstr_t varNull("");
varOutput = pRstAuthors->GetString(adClipString, lRecCount, varTab, varRet, varNull);
printf("State = '%s'\n", strState);
printf ("Name Address City\n");
printf ("%s\n", (LPCTSTR)varOutput);
}
else
printf("\nNo rows found for state = '%s'\n", pState);
}
catch(_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
PrintProviderError(pConnection);
PrintComError(e);
}
Sample Input
MD
Sample Output
Enter a state (CA, IN, KS, MD, MI, OR, TN, UT): State = 'md'
Name Address City
Sylvia Panteley 1956 Arlington Pl. Rockville
See Also
GetString Method (ADO )
Recordset Object (ADO )
Description Property
10/1/2018 • 2 minutes to read • Edit Online
Return Value
Returns a String value that contains a description of the error.
Remarks
Use the Description property to obtain a short description of the error. Display this property to alert the user to
an error that you cannot or do not want to handle. The string will come from either ADO or a provider.
Providers are responsible for passing specific error text to ADO. ADO adds an Error object to the Errors
collection for each provider error or warning it receives. Enumerate the Errors collection to trace the errors that
the provider passes.
Applies To
Error Object
See Also
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VB )
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VC++)
HelpContext, HelpFile Properties
Number Property (ADO )
Source Property (ADO Error)
CommandTypeEnum
10/1/2018 • 2 minutes to read • Edit Online
- CommandText is interpreted as a
textual definition of a command or
stored procedure call. This is the same
behavior as adCmdText.
- CommandText is the name of a
stored procedure. This is the same
behavior as adCmdStoredProc.
- CommandText is interpreted as the
name of a table. All columns are
returned by an internally generated
SQL query. This is the same behavior
as adCmdTable.
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.CommandType.UNSPECIFIED
AdoEnums.CommandType.TEXT
AdoEnums.CommandType.TABLE
AdoEnums.CommandType.STOREDPROC
AdoEnums.CommandType.UNKNOWN
AdoEnums.CommandType.FILE
AdoEnums.CommandType.TABLEDIRECT
Applies To
Requery Method
ADO Object Model
10/1/2018 • 2 minutes to read • Edit Online
The following figures show the ADO objects and their collections.
See Also
ADO Collections
ADO Dynamic Properties
ADO Enumerated Constants
Appendix B: ADO Errors
ADO Events
ADO Methods
ADO Objects and Interfaces
ADO Properties
BeginTrans, CommitTrans, and RollbackTrans
Methods Example (VC++)
10/1/2018 • 4 minutes to read • Edit Online
This example changes the book type of all psychology books in the Titles table of the database. After the
BeginTrans method starts a transaction that isolates all the changes made to the Titles table, the CommitTrans
method saves the changes. You can use the Rollback method to undo changes that you saved using the Update
method.
Example
// BeginBeginTransCpp.cpp
// compile with: /EHsc /c
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <stdio.h>
#include <ole2.h>
#include <conio.h>
#include <assert.h>
#include <malloc.h>
#include "icrsint.h"
public:
CHAR m_szT_title[150];
ULONG lT_titleStatus;
CHAR m_szT_type[40];
ULONG lT_typeStatus;
};
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
BeginTransX();
::CoUninitialize();
}
void BeginTransX() {
// Define ADO object pointers, initialize pointers on define. These are in the ADODB:: namespace.
_RecordsetPtr rstTitles = NULL;
_ConnectionPtr pConnection = NULL;
char * token1, * token2;
// Define Other Variables
HRESULT hr = S_OK;
IADORecordBinding *picRs = NULL; // Interface Pointer declared
CTitlesRs titlrs;
_bstr_t strTitle;
_bstr_t strMessage;
LPSTR p_TempStr = NULL;
char chKey;
int i = 0;
try {
// open connection.
_bstr_t strCnn("Provider='sqloledb';Data Source='My_Data_Source'; Initial Catalog='pubs';Integrated
Security='SSPI';");
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
rstTitles.CreateInstance(__uuidof(Recordset));
rstTitles->CursorType = adOpenDynamic;
rstTitles->LockType = adLockPessimistic;
rstTitles->MoveFirst();
pConnection->BeginTrans();
// Loop through recordset, prompt user to change the type for a specified title.
// Allocate memory to p_TempStr string pointer.
p_TempStr = (LPSTR) malloc(sizeof(titlrs.m_szT_type));
if (chKey == 'y') {
// Set last character of destination string to NULL.
titlrs.m_szT_type[sizeof(titlrs.m_szT_type)-1] = '\0';
// Copy "self_help" title field. The source string will get truncated
// if its length is longer than length of destination string, minus one.
strncpy_s(titlrs.m_szT_type, _countof(titlrs.m_szT_type), "self_help",
sizeof(titlrs.m_szT_type) - 1);
picRs->Update(&titlrs);
}
}
rstTitles->MoveNext();
}
// Ask if the User wants to commit to all the changes made above
printf("\n\n Save all changes(y/n)?");
do {
chKey = _getch();
} while (chKey != 'y' && chKey !='n');
if (chKey == 'y')
// Save the changes to the title table
pConnection->CommitTrans();
else
// Unsave the changes to the title table
pConnection->RollbackTrans();
while (!rstTitles->EndOfFile) {
i = i + 1;
if (i % 23 == 0) {
printf("\nPress any key to continue...");
_getch();
if (!strcmp(p_TempStr,"self_help")) {
// Set final character of destination string to NULL.
titlrs.m_szT_type[sizeof(titlrs.m_szT_type)-1] = '\0';
titlrs.m_szT_type[sizeof(titlrs.m_szT_type)-1] = '\0';
// The source string will get truncated if its length is longer than the length
// of the destination string minus one.
strncpy_s(titlrs.m_szT_type, _countof(titlrs.m_szT_type), "psychology", sizeof(titlrs.m_szT_type)
- 1);
picRs->Update(&titlrs);
}
rstTitles->MoveNext();
}
}
catch(_com_error &e) {
// Notify the user of errors if any.
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
PrintProviderError(pConnection);
if (rstTitles)
if (rstTitles->State == adStateOpen)
rstTitles->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
};
if ( (pConnection->Errors->Count) > 0) {
nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for (i = 0 ; i < nCount ; i++) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
BeginTrans, CommitTrans, and RollbackTrans Methods (ADO )
Update Method
Stream Property
10/1/2018 • 2 minutes to read • Edit Online
Syntax
HRESULT get_Stream([out, retval] IUnknown** ppStream);
HRESULT put_Stream([in] IUnknown* pStream);
Parameters
ppStream
Pointer to an OLE DB Stream object.
pStream
An OLE DB Stream object.
Return Values
This property method returns the standard HRESULT values. This includes S_OK and E_FAIL.
Applies To
ADOStreamConstruction Interface
CacheSize Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Indicates the number of records from a Recordset object that are cached locally in memory.
Remarks
Use the CacheSize property to control how many records to retrieve at one time into local memory from the
provider. For example, if the CacheSize is 10, after first opening the Recordset object, the provider retrieves the
first 10 records into local memory. As you move through the Recordset object, the provider returns the data
from the local memory buffer. As soon as you move past the last record in the cache, the provider retrieves the
next 10 records from the data source into the cache.
NOTE
CacheSize is based on the Maximum Open Rows provider-specific property (in the Properties collection of the
Recordset object). You cannot set CacheSize to a value greater than Maximum Open Rows. To modify the number of
rows which can be opened by the provider, set Maximum Open Rows.
The value of CacheSize can be adjusted during the life of the Recordset object, but changing this value only
affects the number of records in the cache after subsequent retrievals from the data source. Changing the
property value alone will not change the current contents of the cache.
If there are fewer records to retrieve than CacheSize specifies, the provider returns the remaining records and
no error occurs.
A CacheSize setting of zero is not allowed and returns an error.
Records retrieved from the cache don't reflect concurrent changes that other users made to the source data. To
force an update of all the cached data, use the Resync method.
If CacheSize is set to a value greater than one, the navigation methods (Move, MoveFirst, MoveLast, MoveNext,
and MovePrevious) may result in navigation to a deleted record, if deletion occurs after the records were
retrieved. After the initial fetch, subsequent deletions will not be reflected in your data cache until you attempt to
access a data value from a deleted row. However, setting CacheSize to one eliminates this issue since deleted
rows cannot be fetched.
Applies To
Recordset Object (ADO )
See Also
CacheSize Property Example (VB )
CacheSize Property Example (VC++)
CacheSize Property Example (JScript)
Parameters Collection (ADO)
11/26/2018 • 3 minutes to read • Edit Online
Remarks
A Command object has a Parameters collection made up of Parameter objects.
Using the Refresh method on a Command object's Parameters collection retrieves provider parameter
information for the stored procedure or parameterized query specified in the Command object. Some
providers do not support stored procedure calls or parameterized queries; calling the Refresh method on
the Parameters collection when using such a provider will return an error.
If you have not defined your own Parameter objects and you access the Parameters collection before
calling the Refresh method, ADO will automatically call the method and populate the collection for you.
You can minimize calls to the provider to improve performance if you know the properties of the
parameters associated with the stored procedure or parameterized query you wish to call. Use the
CreateParameter method to create Parameter objects with the appropriate property settings and use the
Append method to add them to the Parameters collection. This lets you set and return parameter values
without having to call the provider for the parameter information. If you are writing to a provider that does
not supply parameter information, you must manually populate the Parameters collection using this
method to be able to use parameters at all. Use the Delete method to remove Parameter objects from the
Parameters collection if necessary.
The objects in the Parameters collection of a Recordset go out of scope (therefore becoming unavailable)
when the Recordset is closed.
When calling a stored procedure with Command, the return value/output parameter of a stored procedure
is retrieved as follows:
1. When calling a stored procedure that has no parameters, the Refresh method on the Parameters
collection should be called before calling the Execute method on the Command object.
2. When calling a stored procedure with parameters and explicitly appending a parameter to the
Parameters collection with Append, the return value/output parameter should be appended to the
Parameters collection. The return value must first be appended to the Parameters collection. Use
Append to add the other parameters into the Parameters collection in the order of definition. For
example, the stored procedure SPWithParam has two parameters. The first parameter, InParam, is
an input parameter defined as adVarChar (20), and the second parameter, OutParam, is an output
parameter defined as adVarChar (20). You can retrieve the return value/output parameter with the
following code.
' Open Connection Conn
set ccmd = CreateObject("ADODB.Command")
ccmd.Activeconnection= Conn
ccmd.CommandText="SPWithParam"
ccmd.commandType = 4 'adCmdStoredProc
ccmd.execute()
3. When calling a stored procedure with parameters and configuring the parameters by calling the
Item method on the Parameters collection, the return value/output parameter of the stored
procedure can be retrieved from the Parameters collection. For example, the stored procedure
SPWithParam has two parameters. The first parameter, InParam, is an input parameter defined as
adVarChar (20), and the second parameter, OutParam, is an output parameter defined as adVarChar
(20). You can retrieve the return value/output parameter with the following code.
ccmd.CommandText="SPWithParam"
ccmd.commandType = 4 'adCmdStoredProc
See Also
Append Method (ADO )
CreateParameter Method (ADO )
Parameter Object
AbsolutePosition and CursorLocation Properties
Example (VC++)
10/1/2018 • 3 minutes to read • Edit Online
This example demonstrates how the AbsolutePosition property can track the progress of a loop that enumerates
all the records of a Recordset. It uses the CursorLocation property to enable the AbsolutePosition property by
setting the cursor to a client cursor.
// BeginAbsolutePositionCpp.cpp
// compile with: /EHsc /c
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include "conio.h"
#include "icrsint.h"
public:
CHAR m_szau_lname[41];
ULONG lau_lnameStatus;
};
//Function Declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void AbsolutePositionX();
void AbsolutePosition2X();
void PrintProviderError(_ConnectionPtr pConnection);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
AbsolutePositionX();
AbsolutePosition2X();
::CoUninitialize();
}
void AbsolutePositionX() {
HRESULT hr = S_OK;
try {
// Open a recordset.
TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));
// Explicitly pass the default Cursor type and LockType to the recordset.
TESTHR(pRstEmployees->Open("employee", strCnn, adOpenForwardOnly, adLockReadOnly, adCmdTable));
strMessage= "";
// Enumerate recordset
do {
// Display current record information.
printf("Employee : %s \n record %ld of %d",
emprs.lau_lnameStatus == adFldOK ?
emprs.m_szau_lname : "<NULL>",
pRstEmployees->AbsolutePosition,
pRstEmployees->RecordCount);
printf("\nContinue?(y/n) :");
do {
chKey = _getch();
} while (chKey != 'y' && chKey !='n');
if (chKey == 'n')
break;
strMessage = "";
pRstEmployees->MoveNext();
} while (!(pRstEmployees->EndOfFile));
}
catch(_com_error &e) {
// Notify the user of errors, if any.
_variant_t vtConnect = pRstEmployees->GetActiveConnection();
if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
}
void AbsolutePosition2X() {
HRESULT hr = S_OK;
try {
// Open a recordset.
TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));
// Explicitly pass the default Cursor type and LockType to the Recordset.
TESTHR(pRstEmployees->Open("employee", strCnn, adOpenStatic, adLockReadOnly, adCmdTable));
pRstEmployees->AbsolutePosition = (PositionEnum)lGoToPos;
if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
}
if ( (pConnection->Errors->Count) > 0) {
nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
AbsolutePosition Property (ADO )
CursorLocation Property (ADO )
Recordset Object (ADO )
Value Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the Value property to set or return data from Field objects, to set or return parameter values with
Parameter objects, or to set or return property settings with Property objects. Whether the Value property
is read/write or read-only depends upon numerous factors. See the respective object topics for more
information.
ADO allows setting and returning long binary data with the Value property.
NOTE
For Parameter objects, ADO reads the Value property only once from the provider. If a command contains a
Parameter whose Value property is empty, and you create a Recordset from the command, ensure that you first close
the Recordset before retrieving the Value property. Otherwise, for some providers, the Value property may be empty,
and won't contain the correct value.
For new Field objects that have been appended to the Fields collection of a Record object, the Value property must be
set before any other Field properties can be specified. First, a specific value for the Value property must have been
assigned and Update on the Fields collection called. Then, other properties such as Type or Attributes can be accessed.
Applies To
See Also
Value Property Example (VB ) Value Property Example (VC++)
Bookmark Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Indicates a bookmark that uniquely identifies the current record in a Recordset object or sets the current record
in a Recordset object to the record identified by a valid bookmark.
Remarks
Use the Bookmark property to save the position of the current record and return to that record at any time.
Bookmarks are available only in Recordset objects that support bookmark functionality.
When you open a Recordset object, each of its records has a unique bookmark. To save the bookmark for the
current record, assign the value of the Bookmark property to a variable. To quickly return to that record at any
time after moving to a different record, set the Recordset object's Bookmark property to the value of that
variable.
The user may not be able to view the value of the bookmark. Also, users should not expect bookmarks to be
directly comparable, because two bookmarks that refer to the same record may have different values.
If you use the Clone method to create a copy of a Recordset object, the Bookmark property settings for the
original and the duplicate Recordset objects are identical and you can use them interchangeably. However, you
cannot use bookmarks from different Recordset objects interchangeably, even if they were created from the
same source or command.
NOTE
Remote Data Service Usage When used on a client-side Recordset object, the Bookmark property is always available.
Applies To
Recordset Object (ADO )
See Also
BOF, EOF, and Bookmark Properties Example (VB )
BOF, EOF, and Bookmark Properties Example (VC++)
Supports Method
EndOfRecordset Event (ADO)
10/1/2018 • 2 minutes to read • Edit Online
The EndOfRecordset event is called when there is an attempt to move to a row past the end of the Recordset.
Syntax
EndOfRecordset fMoreData, adStatus, pRecordset
Parameters
fMoreData
A VARIANT_BOOL value that, if set to VARIANT_TRUE, indicates more rows have been added to the Recordset.
adStatus
An EventStatusEnum status value.
When EndOfRecordset is called, this parameter is set to adStatusOK if the operation that caused the event was
successful. It is set to adStatusCantDeny if this event cannot request cancellation of the operation that caused
this event.
Before EndOfRecordset returns, set this parameter to adStatusUnwantedEvent to prevent subsequent
notifications.
pRecordset
A Recordset object. The Recordset for which this event occurred.
Remarks
An EndOfRecordset event may occur if the MoveNext operation fails.
This event handler is called when an attempt is made to move past the end of the Recordset object, perhaps as a
result of calling MoveNext. However, while in this event, you could retrieve more records from a database and
append them to the end of the Recordset. In that case, set fMoreData to VARIANT_TRUE, and return from
EndOfRecordset. Then call MoveNext again to access the newly retrieved records.
See Also
ADO Events Model Example (VC++)
ADO Event Handler Summary
Append and CreateParameter Methods Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Append and CreateParameter methods to execute a stored procedure with an input
parameter.
'BeginAppendVB
' Open the Authors Table to get author names for display
' and set cursor client-side
Set rstAuthors = New ADODB.Recordset
strSQLAuthors = "Authors"
rstAuthors.Open strSQLAuthors, Cnxn, adUseClient, adLockOptimistic, adCmdTable
Do Until rstByRoyalty.EOF
strAuthorID = rstByRoyalty!au_id
Debug.Print " " & rstByRoyalty!au_id & ", ";
rstAuthors.Filter = "au_id = '" & strAuthorID & "'"
rstAuthors.Filter = "au_id = '" & strAuthorID & "'"
Debug.Print rstAuthors!au_fname & " " & rstAuthors!au_lname
rstByRoyalty.MoveNext
Loop
' clean up
rstByRoyalty.Close
rstAuthors.Close
Cnxn.Close
Set rstByRoyalty = Nothing
Set rstAuthors = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstByRoyalty Is Nothing Then
If rstByRoyalty.State = adStateOpen Then rstByRoyalty.Close
End If
Set rstByRoyalty = Nothing
See Also
Append Method (ADO )
CreateParameter Method (ADO )
Field Object
Fields Collection (ADO )
Parameter Object
InfoMessage Event (ADO)
10/1/2018 • 2 minutes to read • Edit Online
The InfoMessage event is called whenever a warning occurs during a ConnectionEvent operation.
Syntax
InfoMessage pError, adStatus, pConnection
Parameters
pError
An Error object. This parameter contains any errors that are returned. If multiple errors are returned, enumerate
the Errors collection to find them.
adStatus
An EventStatusEnum status value. If a warning occurs, adStatus is set to adStatusOK and the pError contains the
warning.
Before this event returns, set this parameter to adStatusUnwantedEvent to prevent subsequent notifications.
pConnection
A Connection object. The connection for which the warning occurred. For example, warnings can occur when
opening a Connection object or executing a Command on a Connection.
See Also
ADO Events Model Example (VC++)
ADO Event Handler Summary
Connection Object (ADO )
EditModeEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.EditMode.NONE
AdoEnums.EditMode.INPROGRESS
AdoEnums.EditMode.ADD
AdoEnums.EditMode.DELETE
Applies To
EditMode Property
OpenSchema Method Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the OpenSchema method to display the name and type of each table in the Pubs database.
'BeginOpenSchemaVB
Do Until rstSchema.EOF
Debug.Print "Table name: " & _
rstSchema!TABLE_NAME & vbCr & _
"Table type: " & rstSchema!TABLE_TYPE & vbCr
rstSchema.MoveNext
Loop
' clean up
rstSchema.Close
Cnxn.Close
Set rstSchema = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstSchema Is Nothing Then
If rstSchema.State = adStateOpen Then rstSchema.Close
End If
Set rstSchema = Nothing
This example specifies a TABLE_TYPE query constraint in the OpenSchema method Criteria argument. As a
result, only schema information for the Views specified in the Pubs database are returned. The example then
displays the name(s) and type(s) of each table(s).
Attribute VB_Name = "OpenSchema"
See Also
OpenSchema Method
Recordset Object (ADO )
Type Property Example (Field) (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Type property by displaying the name of the constant that corresponds to the value
of the Type property of all the Field objects in the Employees table. The FieldType function is required for this
procedure to run.
Example
// BeginTypeFieldCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void TypeX();
_bstr_t FieldType(int intType);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
TypeX();
::CoUninitialize();
}
void TypeX() {
// Define string variables.
_bstr_t strCnn("Provider='sqloledb'; Data Source='(local)'; Initial Catalog='pubs'; Integrated
Security='SSPI';");
// Define ADO object pointers, initialize pointers. These are in the ADODB:: namespace.
_RecordsetPtr pRstEmployees = NULL;
FieldsPtr pFldLoop = NULL;
try {
// Open recordset with data from Employee table.
TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));
pRstEmployees->Open ("employee", strCnn, adOpenForwardOnly, adLockReadOnly, adCmdTable);
if ( (pConnection->Errors->Count) > 0 ) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
Field Object
Type Property (ADO )
Recordset Object Properties, Methods, and Events
10/1/2018 • 2 minutes to read • Edit Online
Properties/Collections
AbsolutePage Property
AbsolutePosition Property
ActiveCommand Property
ActiveConnection Property
BOF, EOF Properties
Bookmark Property
CacheSize Property
CursorLocation Property
CursorType Property
DataMember Property
DataSource Property
EditMode Property
Fields Collection
Filter Property
Index Property
LockType Property
MarshalOptions Property
MaxRecords Property
PageCount Property
PageSize Property
Properties Collection
RecordCount Property
Sort Property
Source Property (ADO Recordset)
State Property
Status Property (ADO Recordset)
StayInSync Property
Methods
AddNew Method
Cancel Method
CancelBatch Method
CancelUpdate Method
Clone Method
Close Method
CompareBookmarks Method
Delete Method (ADO Recordset)
Find Method
GetRows Method
GetString Method
Move Method
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods
NextRecordset Method
Open Method (ADO Recordset)
Requery Method
Resync Method
Save Method
Seek Method
Supports Method
Update Method
UpdateBatch Method
Events
EndOfRecordset Event
FetchComplete Event
FetchProgress Event
WillChangeField and FieldChangeComplete Events
WillChangeRecord and RecordChangeComplete Events
WillChangeRecordset and RecordsetChangeComplete Events
WillMove and MoveComplete Events
See Also
Recordset Object (ADO )
NamedParameters Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
When this property is true, ADO passes the value of the Name property of each parameter in the Parameter
collection for the Command Object. The provider uses a parameter name to match parameters in the
CommandText or CommandStream properties. If this property is false (the default), parameter names are
ignored and the provider uses the order of parameters to match values to parameters in the CommandText or
CommandStream properties.
Applies To
Command Object (ADO )
See Also
CommandText Property (ADO )
CommandStream Property (ADO )
Parameters Collection (ADO )
DefaultDatabase Property
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the DefaultDatabase property to set or return the name of the default database on a specific Connection
object.
If there is a default database, SQL strings may use an unqualified syntax to access objects in that database. To
access objects in a database other than the one specified in the DefaultDatabase property, you must qualify
object names with the desired database name. Upon connection, the provider will write default database
information to the DefaultDatabase property. Some providers allow only one database per connection, in which
case you cannot change the DefaultDatabase property.
Some data sources and providers may not support this feature, and may return an error or an empty string.
NOTE
Remote Data Service Usage This property is not available on a client-side Connection object.
Applies To
Connection Object (ADO )
See Also
Provider and DefaultDatabase Properties Example (VB )
Provider and DefaultDatabase Properties Example (VC++)
Status Property (ADO Recordset)
10/1/2018 • 2 minutes to read • Edit Online
Indicates the status of the current record with respect to batch updates or other bulk operations.
Return Value
Returns a sum of one or more RecordStatusEnum values.
Remarks
Use the Status property to see what changes are pending for records modified during batch updating. You can
also use the Status property to view the status of records that fail during bulk operations, such as when you call
the Resync, UpdateBatch, or CancelBatch methods on a Recordset object, or set the Filter property on a
Recordset object to an array of bookmarks. With this property, you can determine how a given record failed
and resolve it accordingly.
Applies To
Recordset Object (ADO )
See Also
Status Property Example (Recordset) (VB )
Status Property Example (VC++)
UpdateBatch and CancelBatch Methods Example
(VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the UpdateBatch method in conjunction with the CancelBatch method.
'BeginUpdateBatchVB
Public Sub Main()
On Error GoTo ErrorHandler
rstTitles.MoveFirst
' Loop through recordset and ask user if she wants
' to change the type for a specified title.
Do Until rstTitles.EOF
If Trim(rstTitles!Type) = "psychology" Then
strTitle = rstTitles!Title
strMessage = "Title: " & strTitle & vbCr & _
"Change type to self help?"
rstTitles.MoveNext
Loop
' clean up
rstTitles.Close
Cnxn.Close
Set rstTitles = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstTitles Is Nothing Then
If rstTitles.State = adStateOpen Then rstTitles.Close
End If
Set rstTitles = Nothing
See Also
CancelBatch Method (ADO )
UpdateBatch Method
Source Property (ADO Error)
10/12/2018 • 2 minutes to read • Edit Online
Indicates the name of the object or application that originally generated an error.
Return Value
Returns a String value that indicates the name of an object or application.
Remarks
Use the Source property on an Error object to determine the name of the object or application that originally
generated an error. This could be the object's class name or programmatic ID. For errors in ADO, the property
value will be ADODB.ObjectName, where ObjectName is the name of the object that triggered the error. For
ADOX and ADO MD, the value will be ADOX.ObjectName and ADOMD.ObjectName, respectively.
Based on the error documentation from the Source, Number, and Description properties of Error objects, you
can write code that will handle the error appropriately.
The Source property is read-only for Error objects.
Applies To
Error Object
See Also
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VB )
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VC++)
Description Property
HelpContext, HelpFile Properties
Number Property (ADO )
Source Property (ADO Record)
Source Property (ADO Recordset)
MarshalOptionsEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.MarshalOptions.ALL
AdoEnums.MarshalOptions.MODIFIEDONLY
Applies To
MarshalOptions Property (ADO )
DefinedSize Property
10/1/2018 • 2 minutes to read • Edit Online
Return Value
Returns a Long value that reflects the defined size of a field, which depends on the data type of the field object;
see Type for more information. For a field that uses a fixed-length data type, the return value is the size of the
data type in bytes. For a field that uses a variable-length data type, this is one of the following:
1. The maximum length of the field in characters (for adVarChar and adVarWChar) or in bytes (for
adVarBinary, and adVarNumeric) if the field has a defined length. For example, adVarChar(5) field has
a maximum length of 5.
2. The maximum length of the data type in characters (for adChar and adWChar) or in bytes (for adBinary
and adNumeric) if the field does not have a defined length.
3. ~0 (bitwise, the value is not 0; all bits are set to 1) if neither the field nor the data type has a defined
maximum length.
4. For data types that do not have a length, this is set to ~0 (bitwise, the value is not 0; all bits are set to 1).
Remarks
Use the DefinedSize property to determine the data capacity of a Field object.
The DefinedSize and ActualSize properties are different. For example, consider a Field object with a declared
type of adVarChar and a DefinedSize property value of 50, containing a single character. The ActualSize
property value it returns is the length in bytes of the single character.
Applies To
Field Object
See Also
ActualSize and DefinedSize Properties Example (VB )
ActualSize and DefinedSize Properties Example (VC++)
ActualSize Property (ADO )
WillChangeField and FieldChangeComplete Events
(ADO)
10/1/2018 • 2 minutes to read • Edit Online
The WillChangeField event is called before a pending operation changes the value of one or more Field objects
in the Recordset. The FieldChangeComplete event is called after the value of one or more Field objects has
changed.
Syntax
WillChangeField cFields, Fields, adStatus, pRecordset
FieldChangeComplete cFields, Fields, pError, adStatus, pRecordset
Parameters
cFields
A Long that indicates the number of Field objects in Fields.
Fields
For WillChangeField, the Fields parameter is an array of Variants that contains Field objects with the original
values. For FieldChangeComplete, the Fields parameter is an array of Variants that contains Field objects with
the changed values.
pError
An Error object. It describes the error that occurred if the value of adStatus is adStatusErrorsOccurred;
otherwise it is not set.
adStatus
An EventStatusEnum status value.
When WillChangeField is called, this parameter is set to adStatusOK if the operation that caused the event was
successful. It is set to adStatusCantDeny if this event cannot request cancellation of the pending operation.
When FieldChangeComplete is called, this parameter is set to adStatusOK if the operation that caused the
event was successful, or to adStatusErrorsOccurred if the operation failed.
Before WillChangeField returns, set this parameter to adStatusCancel to request cancellation of the pending
operation.
Before FieldChangeComplete returns, set this parameter to adStatusUnwantedEvent to prevent subsequent
notifications.
pRecordset
A Recordset object. The Recordset for which this event occurred.
Remarks
A WillChangeField or FieldChangeComplete event may occur when setting the Value property and calling
the Update method with field and value array parameters.
See Also
ADO Events Model Example (VC++)
ADO Event Handler Summary
Refresh Method Example (VC++)
10/1/2018 • 3 minutes to read • Edit Online
This example demonstrates using the Refresh method to refresh the Parameters collection for a stored procedure
Command object.
Example
// BeginRefreshCpp.cpp
// compile with: /EHsc /c
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
#include "icrsint.h"
END_ADO_BINDING()
public:
CHAR m_szau_fname[21];
ULONG lau_fnameStatus;
CHAR m_szau_lname[41];
ULONG lau_lnameStatus;
};
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void RefreshX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
if (pstrRet == NULL)
return NULL;
if (!strrchr(strDest, '\n'))
// Exhaust the input buffer.
do {
fgets(strExBuff, sizeof(strExBuff), stdin);
} while (!strrchr(strExBuff, '\n'));
else
// Replace '\n' with '\0'
strDest[strrchr(strDest, '\n') - strDest] = '\0';
return pstrRet;
}
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
RefreshX();
::CoUninitialize();
}
void RefreshX() {
HRESULT hr = S_OK;
// Define ADO object pointers. Initialize pointers on define. These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
_CommandPtr pCmdByRoyalty = NULL;
_RecordsetPtr pRstByRoyalty = NULL;
_RecordsetPtr pRstAuthors = NULL;
IADORecordBinding *picRs = NULL; // Interface Pointer declared.
CAuthorsRs authorsrs; // C++ class object
char * token1;
try {
// Open connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open (strCnn, "", "", adConnectUnspecified);
// Get parameter value and execute the command, storing the results in a recordset.
char *strRoyalty;
char strTemp[5];
do {
printf("\n\nEnter royalty : ");
mygets(strTemp, 5);
_variant_t vtroyal;
vtroyal.vt = VT_I2;
vtroyal.iVal = atoi(strRoyalty);
_variant_t Index;
Index.vt = VT_I2;
Index.iVal = 1;
pCmdByRoyalty->GetParameters()->GetItem(Index)->PutValue(vtroyal);
pRstByRoyalty = pCmdByRoyalty->Execute(NULL,NULL,adCmdStoredProc);
if (pRstByRoyalty)
if (pRstByRoyalty->State == adStateOpen)
pRstByRoyalty->Close();
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
Sample Output
Authors with 25 percent royalty
See Also
Command Object (ADO )
Parameters Collection (ADO )
Refresh Method (ADO )
Close Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
object.Close
Remarks
Use the Close method to close a Connection, a Record, a Recordset, or a Stream object to free any associated
system resources. Closing an object does not remove it from memory; you can change its property settings
and open it again later. To completely eliminate an object from memory, close the object and then set the
object variable to Nothing (in Visual Basic).
Connection
Using the Close method to close a Connection object also closes any active Recordset objects associated
with the connection. A Command object associated with the Connection object you are closing will persist,
but it will no longer be associated with a Connection object; that is, its ActiveConnection property will be set
to Nothing. Also, the Command object's Parameters collection will be cleared of any provider-defined
parameters.
You can later call the Open method to re-establish the connection to the same, or another, data source. While
the Connection object is closed, calling any methods that require an open connection to the data source
generates an error.
Closing a Connection object while there are open Recordset objects on the connection rolls back any
pending changes in all of the Recordset objects. Explicitly closing a Connection object (calling the Close
method) while a transaction is in progress generates an error. If a Connection object falls out of scope while
a transaction is in progress, ADO automatically rolls back the transaction.
Applies To
Connection Object (ADO) Record Object (ADO)
See Also
Open and Close Methods Example (VB )
Open and Close Methods Example (VBScript)
Open and Close Methods Example (VC++)
Open Method (ADO Connection)
Open Method (ADO Recordset)
Save Method
ConnectionString Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the ConnectionString property to specify a data source by passing a detailed connection string containing
a series of argument = value statements separated by semicolons.
ADO supports five arguments for the ConnectionString property; any other arguments pass directly to the
provider without any processing by ADO. The arguments ADO supports are as follows.
ARGUMENT DESCRIPTION
Remote Server= Specifies the path name of the server to use when opening a
client-side connection. (Remote Data Service only.)
After you set the ConnectionString property and open the Connection object, the provider may alter the
contents of the property, for example, by mapping the ADO -defined argument names to their equivalents for
the specific provider.
The ConnectionString property automatically inherits the value used for the ConnectionString argument of
the Open method, so you can override the current ConnectionString property during the Open method call.
Because the File Name argument causes ADO to load the associated provider, you cannot pass both the
Provider and File Name arguments.
The ConnectionString property is read/write when the connection is closed and read-only when it is open.
Duplicates of an argument in the ConnectionString property are ignored. The last instance of any argument is
used.
NOTE
Remote Data Service Usage When used on a client-side Connection object, the ConnectionString property can
include only the Remote Provider and Remote Server parameters.
The following table lists the default ADO provider for each Windows operating system:
(To improve the readability of source code, explicitly specify Windows XP (32-bit)
the provider name in the connection string.)
Windows 2003 Server (32-bit)
Applies To
Connection Object (ADO )
See Also
ConnectionString, ConnectionTimeout, and State Properties Example (VB )
ConnectionString, ConnectionTimeout, and State Properties Example (VC++)
Appendix A: Providers
Execute, Requery, and Clear Methods Example
(VBScript)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Execute method when run from both a Command object and a Connection
object. It also uses the Requery method to retrieve current data in a recordset, and the Clear method to clear the
contents of the Errors collection. The ExecuteCommand and PrintOutput procedures are required for this
procedure to run.
Use the following example in an Active Server Page (ASP ). To view this fully functional example, you must either
have the data source AdvWorks.mdb (installed with the SDK samples) located at C:\Program Files\Microsoft
Platform SDK\Samples\DataAccess\Rds\RDSTest\advworks.mdb or edit the path in the example code to reflect
the actual location of this file. This is a Microsoft Access database file.
Use Find to locate the file Adovbs.inc and place it in the directory you plan to use. Cut and paste the following
code into Notepad or another text editor, and save it as ExecuteVBS.asp. You can view the result in any client
browser.
<BODY>
<H3>ADO Execute Method</H3>
<HR>
<HR>
<H4>Recordset Retrieved Using Connection Object</H4>
<!--- Recordsets retrieved using Execute method of Connection and Command Objects-->
<%
' connection, command and recordset variables
Dim Cnxn, strCnxn
Dim rsCustomers, strSQLCustomers
Dim Cmd
Dim rsProducts, strSQLProducts
<HR>
<H4>Recordset Retrieved Using Command Object</H4>
' clean up
If rsCustomers.State = adStateOpen then
rsCustomers.Close
End If
If rsProducts.State = adStateOpen then
rsProducts.Close
End If
If Cnxn.State = adStateOpen then
Cnxn.Close
End If
Set Cmd = Nothing
Set rsCustomers = Nothing
Set rsProducts = Nothing
Set Cnxn = Nothing
%>
</TABLE>
</BODY>
</HTML>
<!-- EndExecuteVBS -->
See Also
Clear Method (ADO )
Command Object (ADO )
Connection Object (ADO )
Error Object
Errors Collection (ADO )
Execute Method (ADO Command)
Execute Method (ADO Connection)
Recordset Object (ADO )
Requery Method
StayInSync Property Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates how the StayInSync property facilitates accessing rows in a hierarchical Recordset.
The outer loop displays each author's first and last name, state, and identification. The appended Recordset for
each row is retrieved from the Fields collection and automatically assigned to rstTitleAuthor by the StayInSync
property whenever the parent Recordset moves to a new row. The inner loop displays four fields from each row in
the appended recordset.
// BeginStayInSyncCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void StayInSyncX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1 ;
StayInSyncX();
::CoUninitialize();
}
void StayInSyncX() {
HRESULT hr = S_OK;
try {
TESTHR(pRstTitleAuthor.CreateInstance(__uuidof(Recordset)));
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
TESTHR(pRst.CreateInstance(__uuidof(Recordset)));
// Open connection.
pConnection->Open (strCnn, "", "", adConnectUnspecified);
pRst->PutStayInSync(true);
pRstTitleAuthor = pRst->GetFields()->GetItem("chapTitleAuthor")->Value;
while (!(pRst->EndOfFile)) {
while (!(pRst->EndOfFile)) {
printf("\n%s %s %s %s\n", (LPCSTR)(_bstr_t)pRst->
Fields->GetItem("au_fname")->Value,
(LPCSTR)(_bstr_t)pRst->Fields->GetItem("au_lname")->Value,
(LPCSTR)(_bstr_t)pRst->Fields->GetItem("state")->Value,
(LPCSTR)(_bstr_t)pRst->Fields->GetItem("au_id")->Value);
_variant_t vIndex;
while ( !(pRstTitleAuthor->EndOfFile) ) {
vIndex = (short) 0;
printf("%s ",(LPCSTR)(_bstr_t)pRstTitleAuthor->Fields->Item[&vIndex]->Value);
vIndex = (short) 1;
printf("%s ",(LPCSTR)(_bstr_t)pRstTitleAuthor->Fields->Item[&vIndex]->Value);
vIndex = (short) 2;
printf("%s ",(LPCSTR)(_bstr_t)pRstTitleAuthor->Fields->Item[&vIndex]->Value);
vIndex = (short) 3;
printf("%s\n",(LPCSTR)(_bstr_t)pRstTitleAuthor->Fields->Item[&vIndex]->Value);
pRstTitleAuthor->MoveNext();
}
pRst->MoveNext();
}
}
catch(_com_error &e) {
// Notify user of errors, if any. Pass connection pointer accessed from the Recordset.
PrintProviderError(pConnection);
PrintComError(e);
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
Fields Collection (ADO )
Recordset Object (ADO )
StayInSync Property
Command (ADO - WFC Syntax)
10/1/2018 • 2 minutes to read • Edit Online
package com.ms.wfc.data
Constructor
public Command()
public Command(String commandtext)
Methods
The executeUpdate method is a special case method that calls the underlying ADO execute method with certain
parameters. The executeUpdate method does not support the return of a Recordset object, so the execute
method's options parameter is modified with AdoEnums.ExecuteOptions.NORECORDS. After the execute
method completes, its updated RecordsAffected parameter is passed back to the executeUpdate method, which is
finally returned as an int.
Properties
See Also
Command Object (ADO )
CursorLocation Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
This property allows you to choose between various cursor libraries accessible to the provider. Usually, you
can choose between using a client-side cursor library or one that is located on the server.
This property setting affects connections established only after the property has been set. Changing the
CursorLocation property has no effect on existing connections.
Cursors returned by the Execute method inherit this setting. Recordset objects will automatically inherit this
setting from their associated connections.
This property is read/write on a Connection or a closed Recordset, and read-only on an open Recordset.
NOTE
Remote Data Service Usage When used on a client-side Recordset or Connection object, the CursorLocation
property can only be set to adUseClient.
Applies To
See Also
Appendix A: Providers
MarshalOptions Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Indicates which records of the Recordset are to be marshaled back to the server.
Remarks
When using a client-side Recordset, records that have been modified on the client are written back to the middle
tier or Web server through a technique called marshaling, the process of packaging and sending interface
method parameters across thread or process boundaries. Setting the MarshalOptions property can improve
performance when modified remote data is marshaled for updating back to the middle tier or Web server.
NOTE
Remote Data Service Usage This property is used only on a client-side Recordset.
Applies To
Recordset Object (ADO )
See Also
MarshalOptions Property Example (VB )
MarshalOptions Property Example (VC++)
AbsolutePage, PageCount, and PageSize Properties
Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the AbsolutePage, PageCount, and PageSize properties to display names and hire dates from
the Employee table, five records at a time.
// BeginAbsolutePageCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <stdio.h>
#include <ole2.h>
#include "conio.h"
#include "icrsint.h"
END_ADO_BINDING()
public:
CHAR m_szau_lname[41];
ULONG lau_lnameStatus;
CHAR m_szau_fname[41];
ULONG lau_fnameStatus;
CHAR m_szau_hiredate[40];
ULONG lau_hiredateStatus;
};
// Function Declarations.
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void AbsolutePageX();
void PrintProviderError(_ConnectionPtr pConnection);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
AbsolutePageX();
::CoUninitialize();
}
void AbsolutePageX() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace.
_RecordsetPtr pRstEmployees = NULL;
try {
// Open a recordset.
TESTHR(hr = pRstEmployees.CreateInstance(__uuidof(Recordset)));
// Explicitly pass the default Cursor type and LockType to the Recordset here
TESTHR(hr = pRstEmployees->Open("employee", strCnn, adOpenForwardOnly, adLockReadOnly, adCmdTable));
pRstEmployees->MoveNext();
if (pRstEmployees->EndOfFile)
break;
}
}
}
catch(_com_error &e) {
// Notify the user of errors if any.
_variant_t vtConnect = pRstEmployees->GetActiveConnection();
if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
printf("Error:\n");
for ( long iError = 0 ; iError < nCount ; iError++) {
pErr = pConnection->Errors->GetItem(iError);
printf("\t Error number: %x\t%s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
AbsolutePage Property (ADO )
PageCount Property (ADO )
PageSize Property (ADO )
Recordset Object (ADO )
ConnectModeEnum
10/1/2018 • 2 minutes to read • Edit Online
Specifies the available permissions for modifying data in a Connection, opening a Record, or specifying values for
the Mode property of the Record and Stream objects.
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.ConnectMode.READ
AdoEnums.ConnectMode.READWRITE
AdoEnums.ConnectMode.SHAREDENYNONE
AdoEnums.ConnectMode.SHAREDENYREAD
AdoEnums.ConnectMode.SHAREDENYWRITE
AdoEnums.ConnectMode.SHAREEXCLUSIVE
AdoEnums.ConnectMode.UNKNOWN
AdoEnums.ConnectMode.WRITE
Applies To
This example uses the Append and CreateParameter methods to execute a stored procedure with an input
parameter. Cut and paste the following code to Notepad or another text editor, and save it as AppendJS.asp.
<html>
<head>
<title>Append and CreateParameter Methods Example (JScript)</title>
<style>
<!--
body {
font-family: 'Verdana','Arial','Helvetica',sans-serif;
BACKGROUND-COLOR:white;
COLOR:black;
}
-->
</style>
</head>
<body>
<h1>Append and CreateParameter Methods Example (JScript)</h1>
<%
// verify user-input
var iRoyalty = parseInt(Request.Form("RoyaltyValue"));
if (iRoyalty > -1)
{
try
{
// open connection and set cursor location
Cnxn.Open(strCnxn);
Cnxn.CursorLocation = adUseClient;
cmdByRoyalty.ActiveConnection = Cnxn;
cmdByRoyalty.ActiveConnection = Cnxn;
// execute command
rsByRoyalty = cmdByRoyalty.Execute();
// display results
rsAuthor.Open("Authors", Cnxn);
while (!rsByRoyalty.EOF)
{
rsAuthor.Filter = "au_id='" + rsByRoyalty.Fields("au_id") + "'";
// recordset data
strMessage += rsAuthor.Fields("au_fname") + " ";
strMessage += rsAuthor.Fields("au_lname") + " ";
// show result
Response.Write(strMessage);
// et next record
rsByRoyalty.MoveNext;
}
}
catch (e)
{
Response.Write(e.message);
}
finally
{
// clean up
if (rsByRoyalty.State == adStateOpen)
rsByRoyalty.Close;
if (rsAuthor.State == adStateOpen)
rsAuthor.Close;
if (Cnxn.State == adStateOpen)
Cnxn.Close;
rsByRoyalty = null;
rsAuthor = null;
Cnxn = null;
}
}
%>
<hr>
</body>
</html>
<!-- EndAppendJS -->
See Also
Append Method (ADO )
CreateParameter Method (ADO )
Field Object
Fields Collection (ADO )
Parameter Object
Collections (Visual C++ Syntax Index with #import)
10/1/2018 • 2 minutes to read • Edit Online
It is useful to know that collections inherit certain common methods and properties.
All collections inherit the Count property and Refresh method, and all collections add the Item property. The
Errors collection adds the Clear method. The Parameters collection inherits the Append and Delete methods,
while the Fields collection adds the Append, Delete, and Update methods.
Properties Collection
Methods
HRESULT Refresh( );
Properties
Errors Collection
Methods
HRESULT Clear( );
HRESULT Refresh( );
Properties
Parameters Collection
Methods
Properties
Fields Collection
Methods
HRESULT Append( _bstr_t Name, enum DataTypeEnum Type, long DefinedSize, enum FieldAttributeEnum Attrib, const
_variant_t & FieldValue = vtMissing );
HRESULT Delete( const _variant_t & Index );
HRESULT Refresh( );
HRESULT Update( );
Properties
See Also
Errors Collection (ADO )
Fields Collection (ADO )
Parameters Collection (ADO )
Properties Collection (ADO )
BOF, EOF Properties (ADO)
10/1/2018 • 2 minutes to read • Edit Online
BOF Indicates that the current record position is before the first record in a Recordset object.
EOF Indicates that the current record position is after the last record in a Recordset object.
Return Value
The BOF and EOF properties return Boolean values.
Remarks
Use the BOF and EOF properties to determine whether a Recordset object contains records or whether you
have gone beyond the limits of a Recordset object when you move from record to record.
The BOF property returns True (-1) if the current record position is before the first record and False (0) if
the current record position is on or after the first record.
The EOF property returns True if the current record position is after the last record and False if the current
record position is on or before the last record.
If either the BOF or EOF property is True, there is no current record.
If you open a Recordset object containing no records, the BOF and EOF properties are set to True (see the
RecordCount property for more information about this state of a Recordset). When you open a Recordset
object that contains at least one record, the first record is the current record and the BOF and EOF
properties are False.
If you delete the last remaining record in the Recordset object, the BOF and EOF properties may remain
False until you attempt to reposition the current record.
This table shows which Move methods are allowed with different combinations of the BOF and EOF
properties.
Allowing a Move method does not guarantee that the method will successfully locate a record; it only means
that calling the specified Move method will not generate an error.
The following table shows what happens to the BOF and EOF property settings when you call various
Move methods but are unable to successfully locate a record.
BOF EOF
Applies To
Recordset Object (ADO )
See Also
BOF, EOF, and Bookmark Properties Example (VB )
BOF, EOF, and Bookmark Properties Example (VC++)
Clone Method Example (VBScript)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Clone method to create copies of a Recordset and then lets the user position the record
pointer of each copy independently.
Use the following example in an Active Server Page (ASP ). This example uses the Northwind database
distributed with Microsoft Access. Cut and paste the following code to Notepad or another text editor and save it
as CloneVBS.asp. You can view the result in any client browser.
To exercise the example, change the line RsCustomerList.Source = "Customers" to
RsCustomerList.Source = "Products" to count a larger table.
<BODY>
rsCustomers.ActiveConnection = Cnxn
rsCustomers.CursorLocation = adUseClient
rsCustomers.CursorType = adOpenKeyset
rsCustomers.LockType = adLockOptimistic
rsCustomers.Source = strSQLCustomers
rsCustomers.Open
rsCustomers.MoveFirst
rsCount = rsCustomers.RecordCount
rsFirst = rsCustomers("CompanyName")
rsCustomers.MoveLast
rsLast = rsCustomers("CompanyName")
<%
' Show location of DSN data source
Response.Write(Cnxn)
' Clean up
If rsCustomers.State = adStateOpen then
rsCustomers.Close
End If
If rsClone.State = adStateOpen then
rsClone.Close
End If
If Cnxn.State = adStateOpen then
Cnxn.Close
End If
Set rsCustomers = Nothing
Set rsClone = Nothing
Set Cnxn = Nothing
%>
</BODY>
</HTML>
<!-- EndCloneVBS -->
See Also
Clone Method (ADO )
Recordset Object (ADO )
Sort Property
10/1/2018 • 2 minutes to read • Edit Online
Indicates one or more field names on which the Recordset is sorted, and whether each field is sorted in ascending
or descending order.
Remarks
This property requires the CursorLocation property to be set to adUseClient. A temporary index will be created
for each field specified in the Sort property if an index does not already exist.
The sort operation is efficient because data is not physically rearranged, but is simply accessed in the order
specified by the index.
When the value of the Sort property is anything other than an empty string, the Sort property order takes
precedence over the order specified in an ORDER BY clause included in the SQL statement used to open the
Recordset.
The Recordset does not have to be opened before accessing the Sort property; it can be set at any time after the
Recordset object is instantiated.
Setting the Sort property to an empty string will reset the rows to their original order and delete temporary
indexes. Existing indexes will not be deleted.
Suppose a Recordset contains three fields named firstName, middleInitial, and lastName. Set the Sort property
to the string, " lastName DESC, firstName ASC ", which will order the Recordset by last name in descending order,
then by first name in ascending order. The middle initial is ignored.
No field can be named "ASC" or "DESC" because those names conflict with the keywords ASC and DESC. You
can create an alias for a field with a conflicting name by using the AS keyword in the query that returns the
Recordset.
Applies To
Recordset Object (ADO )
See Also
Sort Property Example (VB )
Sort Property Example (VC++)
Optimize Property-Dynamic (ADO )
SortColumn Property (RDS )
SortDirection Property (RDS )
CacheSize Property Example (JScript)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the CacheSize property to show the difference in performance for an operation performed with
and without a 30-record cache. Cut and paste the following code to Notepad or another text editor, and save it as
CacheSizeJS.asp.
<HTML>
<HEAD>
<title>CacheSize Property Example (JScript)</title>
<style>
<!--
body {
font-family: 'Verdana','Arial','Helvetica',sans-serif;
BACKGROUND-COLOR:white;
COLOR:black;
}
.thead2 {
background-color: #800000;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
color: white;
}
.tbody {
text-align: center;
background-color: #f7efde;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
}
-->
</style>
</HEAD>
<BODY>
<h1>CacheSize Property Example (JScript)</h1>
<%
// connection and recordset variables
var Cnxn = Server.CreateObject("ADODB.Connection")
var strCnxn = "Provider='sqloledb';Data Source=" + Request.ServerVariables("SERVER_NAME") + ";" +
"Initial Catalog='Northwind';Integrated Security='SSPI';";
var rsCustomer = Server.CreateObject("ADODB.Recordset");
// caching variables
var Now = new Date();
var Start = Now.getTime();
var End, Cache, NoCache
try
{
// open connection
Cnxn.Open(strCnxn)
<table border="2">
<tr class="thead2">
<th>No Cache</th>
<th>30 Record Cache</th>
</tr>
<tr class="tbody">
<td><%=NoCache%></td>
<td><%=Cache%></td>
</tr>
</table>
</BODY>
</HTML>
<!-- EndCacheSizeJS -->
See Also
CacheSize Property (ADO )
Recordset Object (ADO )
Count Property Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Count property with two collections in the Employee database. The property
obtains the number of objects in each collection, and sets the upper limit for loops that enumerate these
collections. Another way to enumerate these collections without using the Count property would be to use
For Each...Next statements.
'BeginCountVB
' clean up
rstEmployees.Close
Cnxn.Close
Set rstEmployees = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
' clean up
If Not rstEmployees Is Nothing Then
If rstEmployees.State = adStateOpen Then rstEmployees.Close
End If
Set rstEmployees = Nothing
See Also
Count Property (ADO )
ADCPROP_UPDATECRITERIA_ENUM
10/1/2018 • 2 minutes to read • Edit Online
Specifies which fields can be used to detect conflicts during an optimistic update of a row of the data source with a
Recordset object.
Use these constants with the Recordset "Update Criteria" dynamic property, which is referenced in the ADO
Dynamic Property Index and documented in the Microsoft Cursor Service for OLE DB documentation.
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.AdcPropUpdateCriteria.ALLCOLS
AdoEnums.AdcPropUpdateCriteria.KEY
AdoEnums.AdcPropUpdateCriteria.TIMESTAMP
AdoEnums.AdcPropUpdateCriteria.UPDCOLS
IsolationLevel and Mode Properties Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Mode property to open an exclusive connection, and the IsolationLevel property to open a
transaction that is conducted in isolation of other transactions.
'BeginIsolationLevelVB
Cnxn.BeginTrans
' clean up
rstTitles.Close
Cnxn.RollbackTrans
Cnxn.Close
Set rstTitles = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstTitles Is Nothing Then
If rstTitles.State = adStateOpen Then rstTitles.Close
End If
Set rstTitles = Nothing
See Also
Connection Object (ADO )
IsolationLevel Property
Mode Property (ADO )
Seek Method and Index Property Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Recordset object's Seek method and Index property in conjunction with a given Employee
ID, to locate the employee's name in the Employees table of the Nwind.mdb database.
'BeginSeekVB
Public Sub SeekX()
On Error GoTo ErrorHandler
' clean up
rstEmployees.Close
Cnxn.Close
Set rstEmployees = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstEmployees Is Nothing Then
If rstEmployees.State = adStateOpen Then rstEmployees.Close
End If
Set rstEmployees = Nothing
See Also
Index Property
Recordset Object (ADO )
Seek Method
Save and Open Methods Example (VC++)
10/1/2018 • 4 minutes to read • Edit Online
These three examples demonstrate how the Save and Open methods can be used together.
Assume you are going on a business trip and want to take along a table from a database. Before you go, you
access the data as a Recordset and save it in a transportable form. When you arrive at your destination, you access
the Recordset as a local, disconnected Recordset. You make changes to the Recordset, then save it again. Finally,
when you return home, you connect to the database again and update it with the changes you made on the road.
// BeginSaveCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
#include <io.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
bool FileExists();
void SaveX1();
void SaveX2();
void SaveX3();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
::CoUninitialize();
}
try {
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
}
try {
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
// Save changes in ADTG format this time, purely for sake of illustration.
// Note that the previous version is still on the diskette as c:\pubs.xml.
pRstAuthors->Save("c:\\pubs.adtg", adPersistADTG);
}
catch(_com_error &e){
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstAuthors->GetActiveConnection();
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
}
try {
TESTHR(pCnn.CreateInstance(__uuidof(Connection)));
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
pRstAuthors->PutActiveConnection(_variant_t((IDispatch *) pCnn));
pRstAuthors->UpdateBatch(adAffectAll);
}
catch(_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstAuthors->GetActiveConnection();
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
if (pCnn)
if (pCnn)
if (pCnn->State == adStateOpen)
pCnn->Close();
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
bool FileExists() {
struct _finddata_t xml_file;
long hFile;
See Also
Open Method (ADO Recordset)
Recordset Object (ADO )
Save Method
Dialect Property
10/1/2018 • 2 minutes to read • Edit Online
Indicates the dialect of the CommandText or CommandStream properties. The dialect defines the syntax and
general rules that the provider uses to parse the string or stream.
Remarks
ADO does not query the provider when the user reads the value of this property; it returns a string representation
of the value currently stored in the Command object.
When the user sets the Dialect property, ADO validates the GUID and raises an error if the value supplied is not
a valid GUID. See the documentation for your provider to determine the GUID values supported by the Dialect
property.
Applies To
Command Object (ADO )
See Also
Execute Method (ADO Command)
ObjectStateEnum
10/1/2018 • 2 minutes to read • Edit Online
Specifies whether an object is open or closed, connecting to a data source, executing a command, or retrieving
data.
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.ObjectState.CLOSED
AdoEnums.ObjectState.OPEN
AdoEnums.ObjectState.CONNECTING
AdoEnums.ObjectState.EXECUTING
AdoEnums.ObjectState.FETCHING
Applies To
Syntax
recordset.Open Source, ActiveConnection, CursorType, LockType, Options
Parameters
Source
Optional. A Variant that evaluates to a valid Command object, an SQL statement, a table name, a stored
procedure call, a URL, or the name of a file or Stream object containing a persistently stored Recordset.
ActiveConnection
Optional. Either a Variant that evaluates to a valid Connection object variable name, or a String that
contains ConnectionString parameters.
CursorType
Optional. A CursorTypeEnum value that determines the type of cursor that the provider should use when
opening the Recordset. The default value is adOpenForwardOnly.
LockType
Optional. A LockTypeEnum value that determines what type of locking (concurrency) the provider should
use when opening the Recordset. The default value is adLockReadOnly.
Options
Optional. A Long value that indicates how the provider should evaluate the Source argument if it
represents something other than a Command object, or that the Recordset should be restored from a
file where it was previously saved. Can be one or more CommandTypeEnum or ExecuteOptionEnum
values, which can be combined with a bitwise OR operator.
NOTE
If you open a Recordset from a Stream containing a persisted Recordset, using an ExecuteOptionEnum value of
adAsyncFetchNonBlocking will have no effect; the fetch will be synchronous and blocking.
NOTE
The ExecuteOpenEnum values of adExecuteNoRecords or adExecuteStream should not be used with Open.
Remarks
The default cursor for an ADO Recordset is a forward-only, read-only cursor located on the server.
Using the Open method on a Recordset object opens a cursor that represents records from a base table,
the results of a query, or a previously saved Recordset.
Use the optional Source argument to specify a data source using one of the following: a Command
object variable, an SQL statement, a stored procedure, a table name, a URL, or a complete file path name.
If Source is a file path name, it can be a full path ("c:\dir\file.rst"), a relative path ("..\file.rst"), or a URL
("https://files/file.rst").
It is not a good idea to use the Source argument of the Open method to perform an action query that
does not return records because there is no easy way to determine whether the call succeeded. The
Recordset returned by such a query will be closed. To perform a query that does not return records,
such as a SQL INSERT statement, call the Execute method of a Command object or the Execute method
of a Connection object instead.
The ActiveConnection argument corresponds to the ActiveConnection property and specifies in which
connection to open the Recordset object. If you pass a connection definition for this argument, ADO
opens a new connection using the specified parameters. After you open the Recordset with a client-side
cursor by setting the CursorLocation property to adUseClient, you can change the value of this
property to send updates to another provider. Or you can set this property to Nothing (in Microsoft
Visual Basic) or NULL to disconnect the Recordset from any provider. Changing ActiveConnection for a
server-side cursor generates an error, however.
For the other arguments that correspond directly to properties of a Recordset object (Source,
CursorType, and LockType), the relationship of the arguments to the properties is as follows:
The property is read/write before the Recordset object is opened.
The property settings are used unless you pass the corresponding arguments when executing the
Open method. If you pass an argument, it overrides the corresponding property setting, and the
property setting is updated with the argument value.
After you open the Recordset object, these properties become read-only.
NOTE
The ActiveConnection property is read-only for Recordset objects whose Source property is set to a valid
Command object, even if the Recordset object is not open.
If you pass a Command object in the Source argument and also pass an ActiveConnection argument, an
error occurs. The ActiveConnection property of the Command object must already be set to a valid
Connection object or connection string.
If you pass something other than a Command object in the Source argument, you can use the Options
argument to optimize evaluation of the Source argument. If the Options argument is not defined, you
may experience diminished performance because ADO must make calls to the provider to determine if
the argument is an SQL statement, a stored procedure, a URL, or a table name. If you know what Source
type you are using, setting the Options argument instructs ADO to jump directly to the relevant code. If
the Options argument does not match the Source type, an error occurs.
If you pass a Stream object in the Source argument, you should not pass information into the other
arguments. Doing so will generate an error. The ActiveConnection information is not retained when a
Recordset is opened from a Stream.
The default for the Options argument is adCmdFile if no connection is associated with the Recordset.
This will typically be the case for persistently stored Recordset objects.
If the data source returns no records, the provider sets both the BOF and EOF properties to True, and
the current record position is undefined. You can still add new data to this empty Recordset object if the
cursor type allows it.
When you have concluded your operations over an open Recordset object, use the Close method to free
any associated system resources. Closing an object does not remove it from memory; you can change its
property settings and use the Open method to open it again later. To completely eliminate an object
from memory, set the object variable to Nothing.
Before the ActiveConnection property is set, call Open with no operands to create an instance of a
Recordset created by appending fields to the Recordset Fields collection.
If you have set the CursorLocation property to adUseClient, you can retrieve rows asynchronously in
one of two ways. The recommended method is to set Options to adAsyncFetch. Alternatively, you can
use the "Asynchronous Rowset Processing" dynamic property in the Properties collection, but related
retrieved events can be lost if you do not set the Options parameter to adAsyncFetch.
NOTE
Background fetching in the MS Remote provider is supported only through the Open method's Options
parameter.
NOTE
URLs using the http scheme will automatically invoke the Microsoft OLE DB Provider for Internet Publishing. For
more information, see Absolute and Relative URLs.
Certain combinations of CommandTypeEnum and ExecuteOptionEnum values are not valid. For
information about which options cannot be combined, see the topics for the ExecuteOptionEnum, and
CommandTypeEnum.
Applies To
Recordset Object (ADO )
See Also
Open and Close Methods Example (VB )
Open and Close Methods Example (VBScript)
Open and Close Methods Example (VC++)
Save and Open Methods Example (VB )
Open Method (ADO Connection)
Open Method (ADO Record)
Open Method (ADO Stream)
OpenSchema Method
Save Method
MoveFirst, MoveLast, MoveNext, and MovePrevious
Methods Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the MoveFirst, MoveLast, MoveNext, and MovePrevious methods to move the record pointer of
a Recordset based on the supplied command. The MoveAny procedure is required for this procedure to run.
'BeginMoveFirstVB
' Show current record information and get user's method choice
Do
strMessage = "Name: " & rstAuthors!au_fname & " " & _
rstAuthors!au_lname & vbCr & "Record " & _
rstAuthors.AbsolutePosition & " of " & _
rstAuthors.RecordCount & vbCr & vbCr & _
"[1 - MoveFirst, 2 - MoveLast, " & vbCr & _
"3 - MoveNext, 4 - MovePrevious]"
intCommand = Val(Left(InputBox(strMessage), 1))
' Use specified method while trapping for BOF and EOF
Select Case intCommand
Case 1
rstAuthors.MoveFirst
Case 2
rstAuthors.MoveLast
Case 3
Case 3
rstAuthors.MoveNext
If rstAuthors.EOF Then
MsgBox "Already at end of recordset!"
rstAuthors.MoveLast
End If
Case 4
rstAuthors.MovePrevious
If rstAuthors.BOF Then
MsgBox "Already at beginning of recordset!"
rstAuthors.MoveFirst
End If
End Select
Loop
' clean up
rstAuthors.Close
Cnxn.Close
Set rstAuthors = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstAuthors Is Nothing Then
If rstAuthors.State = adStateOpen Then rstAuthors.Close
End If
Set rstAuthors = Nothing
'EndMoveFirstVB
See Also
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods (ADO )
Recordset Object (ADO )
ConvertToString Method Example (VB)
11/13/2018 • 2 minutes to read • Edit Online
'BeginConvertToStringVB
' clean up
rsAuthors.Close
Set rsAuthors = Nothing
Set rdsDC = Nothing
Set rdsDS = Nothing
Set rdsDC = Nothing
ErrorHandler:
End Sub
'EndConvertToStringVB
See Also
ConvertToString Method (RDS )
Recordset Object (ADO )
FetchProgress Event (ADO)
10/1/2018 • 2 minutes to read • Edit Online
The FetchProgressevent is called periodically during a lengthy asynchronous operation to report how many
more rows have currently been retrieved into the Recordset.
Syntax
FetchProgress Progress, MaxProgress, adStatus, pRecordset
Parameters
Progress
A Long value indicating the number of records that have currently been retrieved by the fetch operation.
MaxProgress
A Long value indicating the maximum number of records expected to be retrieved.
adStatus
An EventStatusEnum status value.
pRecordset
A Recordset object that is the object for which the records are being retrieved.
Remarks
When using FetchProgress with a child Recordset, be aware that the Progress and MaxProgress parameter
values are derived from the underlying Cursor Service rowset. The values returned represent the total number of
records in the underlying rowset, not just the number of records in the current chapter.
NOTE
To use FetchProgress with Microsoft Visual Basic, Visual Basic 6.0 or later is required.
See Also
ADO Events Model Example (VC++)
ADO Event Handler Summary
DataSource Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
This property is used to create data-bound controls with the Data Environment. The Data Environment maintains
collections of data (data sources) containing named objects (data members) that will be represented as a
Recordset object*.*
The DataMember and DataSource properties must be used in conjunction.
The object referenced must implement the IDataSource interface and must contain an IRowset interface.
Usage
Dim rs as New ADODB.Recordset
rs.DataMember = "Command" 'Name of the rowset to bind to.
Set rs.DataSource = myDE 'Name of the object containing an IRowset.
Applies To
Recordset Object (ADO )
See Also
DataMember Property
CopyRecordOptionsEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
These constants do not have ADO/WFC equivalents.
Applies To
CopyRecord Method (ADO )
Type Property Example (Property) (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Type property. It is a model of a utility for listing the names and types of a
collection, like Properties, Fields, etc.
We do not need to open the Recordset to access its Properties collection; they come into existence when the
Recordset object is instantiated. However, setting the CursorLocation property to adUseClient adds several
dynamic properties to the Recordset object's Properties collection, making the example a little more interesting.
For sake of illustration, we explicitly use the Item property to access each Property object.
'BeginTypePropertyVB
Public Sub Main()
On Error GoTo ErrorHandler
' clean up
Set rst = Nothing
Exit Sub
ErrorHandler:
' clean up
Set rst = Nothing
End Sub
'EndTypePropertyVB
See Also
Property Object (ADO )
Type Property (ADO )
CreateRecordset Method Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
You can create a Recordset object and specify the column information. You can then insert data into the Recordset
object; the underlying rowset buffers the inserts.
The following code example shows how to define a Recordset by using the RDSServer.DataFactory object. You
can also do this with the RDS.DataControl object.
'BeginRsDefineShapeVB
Sub Main()
On Error GoTo ErrorHandler
vntField2Shape(0) = "Age"
vntField2Shape(1) = CInt(3)
vntField2Shape(2) = CInt(-1)
vntField2Shape(3) = True
vntField3Shape(0) = "DateOfBirth"
vntField3Shape(1) = CInt(7)
vntField3Shape(2) = CInt(-1)
vntField3Shape(3) = True
vntField4Shape(0) = "Balance"
vntField4Shape(1) = CInt(6)
vntField4Shape(2) = CInt(-1)
vntField4Shape(3) = True
Dim fields(3)
fields(0) = vntField1Shape(0)
fields(1) = vntField2Shape(0)
fields(2) = vntField3Shape(0)
fields(3) = vntField4Shape(0)
fieldVals(0) = "Mary"
fieldVals(1) = 6
fieldVals(2) = CDate(#6/5/1996#)
fieldVals(3) = 31
NewRs.AddNew fields, fieldVals
fieldVals(0) = "Alex"
fieldVals(1) = 13
fieldVals(2) = CDate(#1/6/1996#)
fieldVals(3) = 34.0001
NewRs.AddNew fields, fieldVals
fieldVals(0) = "Susan"
fieldVals(1) = 13
fieldVals(2) = CDate(#8/6/1996#)
fieldVals(3) = 0#
NewRs.AddNew fields, fieldVals
NewRs.MoveFirst
'Clean up
If NewRs.State = adStateOpen Then NewRs.Close
Set NewRs = Nothing
Set ADC1 = Nothing
Set ADF = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not NewRs Is Nothing Then
If NewRs.State = adStateOpen Then NewRs.Close
End If
Set NewRs = Nothing
Set ADC1 = Nothing
Set ADF = Nothing
This example displays the value of the Attributes property for Connection, Field, and Property objects. It uses the
Name property to display the name of each Field and Property object.
// BeginAttributesCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
#include "icrsint.h"
END_ADO_BINDING()
public:
CHAR m_szemp_LastName[21];
ULONG lemp_LastNameStatus;
CHAR m_szemp_FirstName[11];
ULONG lemp_FirstNameStatus;
CHAR m_szemp_Faxphone[25];
ULONG lemp_FaxphoneStatus;
};
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void AttributesX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
AttributesX();
::CoUninitialize();
}
void AttributesX() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace
_RecordsetPtr pRstEmployee = NULL;
_ConnectionPtr pConnection = NULL;
FieldsPtr fldLoop = NULL;
FieldsPtr fldLoop = NULL;
PropertiesPtr proLoop = NULL;
try {
// open connection and record set
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open(strCnn, "", "", adConnectUnspecified);
TESTHR(pRstEmployee.CreateInstance(__uuidof(Recordset)));
pRstEmployee->Open("Employee", _variant_t((IDispatch *)pConnection,true), adOpenForwardOnly,
adLockReadOnly, adCmdTable);
PrintProviderError(pConnection);
PrintComError(e);
}
if ( (pConnection->Errors->Count) > 0) {
nCount = pConnection->Errors->Count;
See Also
Attributes Property (ADO )
Connection Object (ADO )
Field Object
Name Property (ADO )
Property Object (ADO )
AbsolutePage, PageCount, and PageSize Properties
Example (JScript)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the AbsolutePage, PageCount and PageSize properties. Cut and paste the following
code to Notepad or another text editor, and save it as AbsolutePageJS.asp.
<html>
<head>
<title>AbsolutePage, PageSize, and PageSize Properties (JScript)</title>
<style>
<!--
BODY {
font-family: 'Verdana','Arial','Helvetica',sans-serif;
BACKGROUND-COLOR:white;
COLOR:black;
}
.thead2 {
background-color: #800000;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
color: white;
}
.tbody {
text-align: center;
background-color: #f7efde;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
}
-->
</style>
</head>
<body bgcolor="White">
<h1>AbsolutePage, PageSize, and PageSize Properties (JScript)</h1>
<%
// connection and recordset variables
var Cnxn = Server.CreateObject("ADODB.Connection")
var strCnxn = "Provider='sqloledb';Data Source=" + Request.ServerVariables("SERVER_NAME") + ";" +
"Initial Catalog='Northwind';Integrated Security='SSPI';";
var rsEmployee = Server.CreateObject("ADODB.Recordset");
// display variables
var strMessage, iRecord, iPageCount;
try
{
// open connection
Cnxn.Open(strCnxn);
// Set PageSize to five to display names and hire dates of five employees at a time
// Set PageSize to five to display names and hire dates of five employees at a time
rsEmployee.PageSize = 5;
iPageCount = rsEmployee.PageCount;
if (rsEmployee.EOF)
break;
}
}
</body>
</html>
<!-- EndAbsolutePageJS -->
See Also
AbsolutePage Property (ADO )
PageCount Property (ADO )
PageSize Property (ADO )
Recordset Object (ADO )
Value Property Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Value property with Field and Property objects by displaying field and property
values for the Employees table.
'BeginValueVB
Public Sub Main()
On Error GoTo ErrorHandler
' clean up
rstEmployees.Close
Cnxn.Close
Set rstEmployees = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstEmployees Is Nothing Then
If rstEmployees.State = adStateOpen Then rstEmployees.Close
End If
Set rstEmployees = Nothing
See Also
Field Object
Property Object (ADO )
Value Property (ADO )
CursorType, LockType, and EditMode Properties
Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates setting the CursorType and LockType properties before opening a Recordset. It also
shows the value of the EditMode property under various conditions. The EditModeOutput function is required for
this procedure to run.
'BeginEditModeVB
' clean up
Cnxn.Close
Set rstEmployees = Nothing
Set rstEmployees = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstEmployees Is Nothing Then
If rstEmployees.State = adStateOpen Then rstEmployees.Close
End If
Set rstEmployees = Nothing
End Sub
End Function
'EndEditModeVB
See Also
CursorType Property (ADO )
CursorTypeEnum
EditMode Property
EditModeEnum
LockType Property (ADO )
LockTypeEnum
Recordset Object (ADO )
DataMember Property
10/1/2018 • 2 minutes to read • Edit Online
Indicates the name of the data member that will be retrieved from the Recordset referenced by the DataSource
property.
Remarks
This property is used to create data-bound controls with the Data Environment. The Data Environment maintains
collections of data (data sources) containing named objects (data members) that will be represented as a
Recordset object.
The DataMember and DataSource properties must be used together.
The DataMember property determines which object specified by the DataSource property will be represented
as a Recordset object. The Recordset object must be closed before this property is set. An error is generated if
the DataMember property is not set before the DataSource property, or if the DataMember name is not
recognized by the object specified in the DataSource property.
Usage
Dim rs as New ADODB.Recordset
rs.DataMember = "Command" 'Name of the rowset to bind to
Set rs.DataSource = myDE 'Name of the object containing an IRowset
Applies To
Recordset Object (ADO )
See Also
DataSource Property (ADO )
DataTypeEnum
10/1/2018 • 2 minutes to read • Edit Online
Specifies the data type of a Field, Parameter, or Property. The corresponding OLE DB type indicator is shown in
parentheses in the description column of the following table.
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.DataType.ARRAY
AdoEnums.DataType.BIGINT
CONSTANT
AdoEnums.DataType.BINARY
AdoEnums.DataType.BOOLEAN
AdoEnums.DataType.BSTR
AdoEnums.DataType.CHAPTER
AdoEnums.DataType.CHAR
AdoEnums.DataType.CURRENCY
AdoEnums.DataType.DATE
AdoEnums.DataType.DBDATE
AdoEnums.DataType.DBTIME
AdoEnums.DataType.DBTIMESTAMP
AdoEnums.DataType.DECIMAL
AdoEnums.DataType.DOUBLE
AdoEnums.DataType.EMPTY
AdoEnums.DataType.ERROR
AdoEnums.DataType.FILETIME
AdoEnums.DataType.GUID
AdoEnums.DataType.IDISPATCH
AdoEnums.DataType.INTEGER
AdoEnums.DataType.IUNKNOWN
AdoEnums.DataType.LONGVARBINARY
AdoEnums.DataType.LONGVARCHAR
AdoEnums.DataType.LONGVARWCHAR
AdoEnums.DataType.NUMERIC
AdoEnums.DataType.PROPVARIANT
AdoEnums.DataType.SINGLE
CONSTANT
AdoEnums.DataType.SMALLINT
AdoEnums.DataType.TINYINT
AdoEnums.DataType.UNSIGNEDBIGINT
AdoEnums.DataType.UNSIGNEDINT
AdoEnums.DataType.UNSIGNEDSMALLINT
AdoEnums.DataType.UNSIGNEDTINYINT
AdoEnums.DataType.USERDEFINED
AdoEnums.DataType.VARBINARY
AdoEnums.DataType.VARCHAR
AdoEnums.DataType.VARIANT
AdoEnums.DataType.VARNUMERIC
AdoEnums.DataType.VARWCHAR
AdoEnums.DataType.WCHAR
Applies To
Remarks
The Source property returns the Source argument of the Record object Open method. It can contain an
absolute or relative URL string. An absolute URL can be used without setting the ActiveConnection property to
directly open the Record object. An implicit Connection object is created in this case.
The Source property can also contain a reference to an already open Recordset, which opens a Record object
representing the current row in the Recordset.
The Source property could also contain a reference to a Command object which returns a single row of data
from the provider.
If the ActiveConnection property is also set, then the Source property must point to some object that exists
within the scope of that connection. For example, in tree-structured namespaces, if the Source property contains
an absolute URL, it must point to a node that exists inside the scope of the node identified by the URL in the
connection string. If the Source property contains a relative URL, then it is validated within the context set by the
ActiveConnection property.
The Source property is read/write while the Record object is closed, and is read-only while the Record object is
open.
NOTE
URLs using the http scheme will automatically invoke the Microsoft OLE DB Provider for Internet Publishing. For more
information, see Absolute and Relative URLs.
Applies To
Record Object (ADO )
See Also
Source Property (ADO Error)
Source Property (ADO Recordset)
HelpContext, HelpFile Properties
10/1/2018 • 2 minutes to read • Edit Online
Indicates the Help file and topic associated with an Error object.
Return Values
HelpContextID Returns a context ID, as a Long value, for a topic in a Help file.
HelpFile Returns a String value that evaluates to a fully resolved path to a Help file.
Remarks
If a Help file is specified in the HelpFile property, the HelpContext property is used to automatically display
the Help topic it identifies. If there is no relevant help topic available, the HelpContext property returns zero
and the HelpFile property returns a zero-length string ("").
Applies To
Error Object
See Also
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VB )
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VC++)
Description Property
Number Property (ADO )
Source Property (ADO Error)
Value Property Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the Value property with Field and Property objects by displaying field and property
values for the Employees table.
// BeginValueCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void ValueX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
ValueX();
::CoUninitialize();
}
void ValueX() {
HRESULT hr = S_OK;
try {
// Open recordset with data from Employee table.
TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));
pRstEmployees->Open ("employee", strCnn , adOpenForwardOnly, adLockReadOnly, adCmdTable);
case (VT_BOOL):
if(propValue.boolVal)
printf(" %s = True\n\n", (LPCSTR) pPrpLoop->GetItem(vtIndex)->GetName());
else
printf(" %s = False\n\n", (LPCSTR) pPrpLoop->GetItem(vtIndex)->GetName());
break;
case (VT_I4):
printf(" %s = %d\n\n", (LPCSTR) pPrpLoop->GetItem(vtIndex)->GetName(),
pPrpLoop->GetItem(vtIndex)->Value.lVal);
break;
case (VT_EMPTY):
printf(" %s = \n\n", (LPCSTR) pPrpLoop->GetItem(vtIndex)->GetName());
break;
default:
break;
}
}
}
catch (_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstEmployees->GetActiveConnection();
if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
Field Object
Property Object (ADO )
Value Property (ADO )
Move Method Example (VBScript)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Move method to position the record pointer, based on user input.
Use the following example in an Active Server Page (ASP ). To view this fully functional example, you must either
have the data source AdvWorks.mdb (installed with the SDK) located at C:\Program Files\Microsoft Platform
SDK\Samples\DataAccess\Rds\RDSTest\advworks.mdb or edit the path in the example code to reflect the actual
location of this file. This is a Microsoft Access database file.
Use Find to locate the file Adovbs.inc and place it in the directory you plan to use. Cut and paste the following
code to Notepad or another text editor, and save it as MoveVBS.asp. You can view the result in any browser.
Try entering a letter or noninteger to see the error handling work.
Cnxn.Open strCnxn
rsCustomers.ActiveConnection = Cnxn
rsCustomers.CursorLocation = adUseClient
rsCustomers.CursorType = adOpenKeyset
rsCustomers.LockType = adLockOptimistic
rsCustomers.Source = strSQLCustomers
rsCustomers.Open
'Error Handling
If rsCustomers.EOF Then
Session("Clicks") = rsCustomers.RecordCount
Response.Write "This is the Last Record"
rsCustomers.MoveLast
ElseIf rsCustomers.BOF Then
Session("Clicks") = 1
rsCustomers.MoveFirst
Response.Write "This is the First Record"
End If
%>
<TR CLASS=thead1>
<TD>Company Name</TD>
<TD>Contact Name</TD>
<TD>City</TD>
</TR>
<% 'display%>
<TR CLASS=tbody>
<TD> <%= rsCustomers("CompanyName")%> </TD>
<TD> <%= rsCustomers("ContactName")%></TD>
<TD> <%= rsCustomers("City")%> </TD>
</TR>
</TABLE>
<HR>
<Input Type=Button Name=cmdDown Value="< ">
<Input Type=Button Name=cmdUp Value=" >">
<H5>Click Direction Arrows for Previous or Next Record
<BR> <BR>
Sub Move_OnClick
' Make sure move value entered is an integer
If IsNumeric(Document.Form.MoveAmount.Value)Then
Document.Form.MoveAmount.Value = CInt(Document.Form.MoveAmount.Value)
Document.Form.Submit
Else
MsgBox "You Must Enter a Number", ,"ADO-ASP Example"
Document.Form.MoveAmount.Value = 0
End If
End Sub
Sub cmdDown_OnClick
Document.Form.MoveAmount.Value = -1
Document.Form.Submit
End Sub
Sub cmdUp_OnClick
Document.Form.MoveAmount.Value = 1
Document.Form.Submit
End Sub
</Script>
<%
' clean up
If rsCustomers.State = adStateOpen then
rsCustomers.Close
End If
If Cnxn.State = adStateOpen then
Cnxn.Close
End If
%>
</HTML>
<!-- EndMoveVBS -->
See Also
Move Method (ADO )
Recordset Object (ADO )
NumericScale Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the NumericScale property to determine how many digits to the right of the decimal point will be used to
represent values for a numeric Parameter or Field object.
For Parameter objects, the NumericScale property is read/write.
For a Fieldobject, NumericScale is normally read-only. However, for new Field objects that have been
appended to the Fields collection of a Record, NumericScale is read/write only after the Value property for the
Field has been specified and the data provider has successfully added the new Field by calling the Update
method of the Fields collection.
Applies To
See Also
NumericScale and Precision Properties Example (VB )
NumericScale and Precision Properties Example (VC++)
Precision Property (ADO )
Supports Method
10/1/2018 • 2 minutes to read • Edit Online
Syntax
boolean = recordset.Supports(CursorOptions )
Return Value
Returns a Boolean value that indicates whether all of the features identified by the CursorOptions argument
are supported by the provider.
Parameters
CursorOptions
A Long expression that consists of one or more CursorOptionEnum values.
Remarks
Use the Supports method to determine what types of functionality a Recordset object supports. If the
Recordset object supports the features whose corresponding constants are in CursorOptions, the Supports
method returns True. Otherwise, it returns False.
NOTE
Although the Supports method may return True for a given functionality, it does not guarantee that the provider can
make the feature available under all circumstances. The Supports method simply returns whether the provider can
support the specified functionality, assuming certain conditions are met. For example, the Supports method may indicate
that a Recordset object supports updates even though the cursor is based on a multiple table join, some columns of
which are not updatable.
Applies To
Recordset Object (ADO )
See Also
Supports Method Example (VB )
Supports Method Example (VC++)
CursorType Property (ADO )
ADO Events Model Example (VC++)
10/1/2018 • 6 minutes to read • Edit Online
The Visual C++ section of ADO Event Instantiation by Language gives a general description of how to
instantiate the ADO event model. The following is a specific example of instantiating the event model within the
environment created by the #import directive.
The general description uses adoint.h as a reference for method signatures. However, a few details in the
general description change slightly as a result of using the #import directive:
The #import directive resolves typedef's, method signature data types, and modifiers to their
fundamental forms.
The pure virtual methods that must be overwritten are all prefixed by "raw_".
Some of the code simply reflects coding style.
The pointer to IUnknown used by the Advise method is obtained explicitly with a call to
QueryInterface.
You don't need to explicitly code a destructor in the class definitions.
You may want to code more robust implementations of QueryInterface, AddRef, and Release.
The __uuidof() directive is used extensively to obtain interface IDs.
Finally, the example contains some working code.
The example is written as a console application.
You should insert your own code under the comment, " // Do some work ".
All the event handlers default to doing nothing, and canceling further notifications. You should insert the
appropriate code for your application, and allow notifications if required.
// ADO_Events_Model_Example.cpp
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
public:
CConnEvent() { m_cRef = 0; };
~CConnEvent() {};
public:
CRstEvent() { m_cRef = 0; };
~CRstEvent() {};
if (*ppv == NULL)
return ResultFromScode(E_NOINTERFACE);
AddRef();
AddRef();
return NOERROR;
}
STDMETHODIMP_(ULONG) CRstEvent::AddRef() {
return ++m_cRef;
};
STDMETHODIMP_(ULONG) CRstEvent::Release() {
if (0 != --m_cRef)
return m_cRef;
delete this;
return 0;
}
if (*ppv == NULL)
return ResultFromScode(E_NOINTERFACE);
AddRef();
return NOERROR;
}
STDMETHODIMP_(ULONG) CConnEvent::AddRef() {
return ++m_cRef;
};
STDMETHODIMP_(ULONG) CConnEvent::Release() {
if (0 != --m_cRef)
return m_cRef;
delete this;
return 0;
}
int main() {
HRESULT hr;
DWORD dwConnEvt;
DWORD dwRstEvt;
IConnectionPointContainer *pCPC = NULL;
IConnectionPoint *pCP = NULL;
IUnknown *pUnk = NULL;
CRstEvent *pRstEvent = NULL;
CConnEvent *pConnEvent= NULL;
int rc = 0;
_RecordsetPtr pRst;
_ConnectionPtr pConn;
::CoInitialize(NULL);
hr = pConn.CreateInstance(__uuidof(Connection));
if (FAILED(hr))
return rc;
hr = pRst.CreateInstance(__uuidof(Recordset));
if (FAILED(hr))
return rc;
if (FAILED(hr))
return rc;
hr = pCPC->FindConnectionPoint(__uuidof(ConnectionEvents), &pCP);
hr = pCPC->FindConnectionPoint(__uuidof(ConnectionEvents), &pCP);
pCPC->Release();
if (FAILED(hr))
return rc;
if (FAILED(hr))
return rc;
hr = pCP->Advise(pUnk, &dwConnEvt);
pCP->Release();
if (FAILED(hr))
return rc;
if (FAILED(hr))
return rc;
hr = pCPC->FindConnectionPoint(__uuidof(RecordsetEvents), &pCP);
pCPC->Release();
if (FAILED(hr))
return rc;
if (FAILED(hr))
return rc;
hr = pCP->Advise(pUnk, &dwRstEvt);
pCP->Release();
if (FAILED(hr))
return rc;
// Do some work
pConn->Open("dsn=DataPubs;", "", "", adConnectUnspecified);
pRst->Open("SELECT * FROM authors", (IDispatch *) pConn, adOpenStatic, adLockReadOnly, adCmdText);
pRst->MoveFirst();
while (pRst->EndOfFile == FALSE) {
wprintf(L"Name = '%s'\n", (wchar_t*) ((_bstr_t) pRst->Fields->GetItem("au_lname")->Value));
pRst->MoveNext();
}
pRst->Close();
pConn->Close();
if (FAILED(hr))
return rc;
hr = pCPC->FindConnectionPoint(__uuidof(ConnectionEvents), &pCP);
pCPC->Release();
if (FAILED(hr))
return rc;
hr = pCP->Unadvise( dwConnEvt );
pCP->Release();
if (FAILED(hr))
return rc;
if (FAILED(hr))
return rc;
hr = pCPC->FindConnectionPoint(__uuidof(RecordsetEvents), &pCP);
pCPC->Release();
if (FAILED(hr))
return rc;
hr = pCP->Unadvise( dwRstEvt );
pCP->Release();
if (FAILED(hr))
return rc;
CoUninitialize();
}
Errors Collection (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Contains all the Error objects created in response to a single provider-related failure.
Remarks
Any operation involving ADO objects can generate one or more provider errors. As each error occurs, one
or more Error objects can be placed in the Errors collection of the Connection object. When another ADO
operation generates an error, the Errors collection is cleared, and the new set of Error objects can be placed
in the Errors collection.
Each Error object represents a specific provider error, not an ADO error. ADO errors are exposed to the run-
time exception-handling mechanism. For example, in Microsoft Visual Basic, the occurrence of an ADO -
specific error will trigger an onError event and appear in the Err object.
ADO operations that don't generate an error have no effect on the Errors collection. Use the Clear method
to manually clear the Errors collection.
The set of Error objects in the Errors collection describes all errors that occurred in response to a single
statement. Enumerating the specific errors in the Errors collection enables your error-handling routines to
more precisely determine the cause and origin of an error, and take appropriate steps to recover.
Some properties and methods return warnings that appear as Error objects in the Errors collection but do
not halt a program's execution. Before you call the Resync, UpdateBatch, or CancelBatch methods on a
Recordset object, the Open method on a Connection object, or set the Filter property on a Recordset
object, call the Clear method on the Errors collection. That way you can read the Count property of the
Errors collection to test for returned warnings.
NOTE
See the Error object topic for a more detailed explanation of the way a single ADO operation can generate multiple
errors.
See Also
Error Object
Appendix A: Providers
StringFormatEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.StringFormat.CLIPSTRING
Applies To
GetString Method (ADO )
DeleteRecord Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Record.DeleteRecord Source, Async
Parameters
Source
Optional. A String value that contains a URL identifying the entity (for example, the file or directory) to be
deleted. If Source is omitted or specifies an empty string, the entity represented by the current Record is deleted.
If the Record is a collection record (RecordType of adCollectionRecord, such as a directory) all children (for
example, subdirectories) will also be deleted.
Async
Optional. A Boolean value that, when True, specifies that the delete operation is asychronous.
Remarks
Operations on the object represented by this Record may fail after this method completes. After calling
DeleteRecord, the Record should be closed because the behavior of the Record may become unpredictable
depending upon when the provider updates the Record with the data source.
If this Record was obtained from a Recordset, then the results of this operation will not be reflected immediately
in the Recordset. Refresh the Recordset by closing and re-opening it, or by executing the Recordset Requery
method, the Update method, or the Resync method.
NOTE
URLs using the http scheme will automatically invoke the Microsoft OLE DB Provider for Internet Publishing. For more
information, see Absolute and Relative URLs.
Applies To
Record Object (ADO )
See Also
Delete Method (ADO Fields Collection)
Delete Method (ADO Parameters Collection)
Delete Method (ADO Recordset)
Delete Method (ADO Fields Collection)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Fields.Delete Field
Parameters
Field
A Variant that designates the Field object to delete. This parameter can be the name of the Field object or the
ordinal position of the Field object itself.
Remarks
Calling the Fields.Delete method on an open Recordset causes a run-time error.
Applies To
Fields Collection (ADO )
See Also
Delete Method (ADO Parameters Collection)
Delete Method (ADO Recordset)
DeleteRecord Method (ADO )
Attributes and Name Properties Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example displays the value of the Attributes property for Connection, Field, and Property objects. It uses the
Name property to display the name of each Field and Property object.
' BeginAttributesVB
Sub Main()
On Error GoTo AttributesXError
With rstEmployees
' Get user input.
strMessage = "Enter fax number for " & _
!FirstName & " " & !LastName & "." & vbCr & _
"[? - unknown, X - has no fax]"
strInput = UCase(InputBox(strMessage))
If strInput <> "" Then
Select Case strInput
Case "?"
!FaxPhone = Null
Case "X"
!FaxPhone = ""
Case Else
!FaxPhone = strInput
End Select
.Update
If IsNull(!FaxPhone) Then
Debug.Print "[Unknown]"
Else
If !FaxPhone = "" Then
Debug.Print "[Has no fax]"
Debug.Print "[Has no fax]"
Else
Debug.Print !FaxPhone
End If
End If
End If
.Close
End With
'Clean up
tblEmp.Columns.Delete colTemp.Name
cnn.Close
Set rstEmployees = Nothing
Set cat = Nothing
Set colTemp = Nothing
Set cnn = Nothing
Exit Sub
AttributesXError:
End Sub
' EndAttributesVB
See Also
Attributes Property (ADO )
Connection Object (ADO )
Field Object
Name Property (ADO )
Property Object (ADO )
CompareBookmarks Method Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the CompareBookmarks method. The relative value of bookmarks is seldom needed
unless a particular bookmark is somehow special.
Designate a random row of a Recordset derived from the Authors table as the target of a search. Then display the
position of each row relative to that target.
// BeginCompareBookmarksCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <stdlib.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void CompareBookMarksX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
CompareBookMarksX();
::CoUninitialize();
}
void CompareBookMarksX() {
HRESULT hr = S_OK;
if (result == adCompareNotEqual)
printf("Row %d: Bookmarks are not equal. %d\n", count, result);
else if (result == adCompareNotComparable)
printf("Row %d: Bookmarks are not comparable.\n", count);
else {
switch(result) {
case adCompareLessThan:
strAns = "less than";
break;
case adCompareEqual:
strAns = "equal to";
break;
case adCompareGreaterThan:
strAns = "greater than";
break;
default:
strAns = "in error comparing to";
break;
}
printf ("Row position %d is %s the target.\n",
count,(LPCSTR)strAns);
}
count++;
pRstAuthors->MoveNext();
}
}
catch(_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstAuthors->GetActiveConnection();
if ( (pConnection->Errors->Count) > 0) {
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for (long i = 0 ; i < nCount ; i++) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s\n", pErr->Number, pErr->Description);
}
}
}
See Also
CompareBookmarks Method (ADO )
Recordset Object (ADO )
Version Property Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Version property of a Connection object to display the current ADO version. It also uses
several dynamic properties to show:
Current DBMS name and version.
OLE DB version.
Provider name and version.
ODBC version.
ODBC driver name and version.
NOTE
If you are connecting to a data source provider that supports Windows authentication, you should specify
Trusted_Connection=yes or Integrated Security = SSPI instead of user ID and password information in the connection
string.
// BeginVersionCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void VersionX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
VersionX();
::CoUninitialize();
}
void VersionX() {
HRESULT hr = S_OK;
try {
// Open connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open (strCnn, "", "", adConnectUnspecified);
printf("ADO Version : %s\n\n",(LPCSTR) pConnection->Version);
printf("DBMS Name : %s\n\n",(LPCSTR) (_bstr_t)
pConnection->Properties->GetItem("DBMS Name")->Value);
printf("DBMS Version : %s\n\n",(LPCSTR) (_bstr_t)
pConnection->Properties->GetItem("DBMS Version")->Value);
printf("OLE DB Version : %s\n\n",(LPCSTR) (_bstr_t)
pConnection->Properties->GetItem("OLE DB Version")->Value);
printf("Provider Name : %s\n\n",(LPCSTR) (_bstr_t)
pConnection->Properties->GetItem("Provider Name")->Value);
printf("Provider Version : %s\n\n",(LPCSTR) (_bstr_t)
pConnection->Properties->GetItem("Provider Version")->Value);
printf("Driver Name : %s\n\n",(LPCSTR) (_bstr_t)
pConnection->Properties->GetItem("Driver Name")->Value);
printf("Driver Version : %s\n\n",(LPCSTR) (_bstr_t)
pConnection->Properties->GetItem("Driver Version")->Value);
printf("Driver ODBC Version : %s\n\n",(LPCSTR) (_bstr_t)
pConnection->Properties->GetItem("Driver ODBC Version")->Value);
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
Connection Object (ADO )
Version Property (ADO )
UpdateBatch Method
10/1/2018 • 2 minutes to read • Edit Online
Syntax
recordset.UpdateBatch AffectRecords, PreserveStatus
Parameters
AffectRecords
Optional. An AffectEnum value that indicates how many records the UpdateBatch method will affect.
PreserveStatus
Optional. A Boolean value that specifies whether or not local changes, as indicated by the Status property,
should be committed. If this value is set to True, the Status property of each record remains unchanged
after the update is completed.
Remarks
Use the UpdateBatch method when modifying a Recordset object in batch update mode to transmit all
changes made in a Recordset object to the underlying database.
If the Recordset object supports batch updating, you can cache multiple changes to one or more records
locally until you call the UpdateBatch method. If you are editing the current record or adding a new record
when you call the UpdateBatch method, ADO will automatically call the Update method to save any
pending changes to the current record before transmitting the batched changes to the provider. You should
use batch updating with either a keyset or static cursor only.
NOTE
Specifying adAffectGroup as the value for this parameter will result in an error when there are no visible records in
the current Recordset (such as a filter for which no records match).
If the attempt to transmit changes fails for any or all records because of a conflict with the underlying data
(for example, a record has already been deleted by another user), the provider returns warnings to the
Errors collection and a run-time error occurs. Use the Filter property ( adFilterAffectedRecords) and the
Status property to locate records with conflicts.
To cancel all pending batch updates, use the CancelBatch method.
If the Unique Table and Update Resync dynamic properties are set, and the Recordset is the result of
executing a JOIN operation on multiple tables, then the execution of the UpdateBatch method is implicitly
followed by the Resync method, depending on the settings of the Update Resync property.
The order in which the individual updates of a batch are performed on the data source is not necessarily the
same as the order in which they were performed on the local Recordset. Update order is dependent upon
the provider. Take this into account when coding updates that are related to one another, such as foreign key
constraints on an insert or update.
Applies To
Recordset Object (ADO )
See Also
UpdateBatch and CancelBatch Methods Example (VB )
UpdateBatch and CancelBatch Methods Example (VC++)
CancelBatch Method (ADO )
Clear Method (ADO )
LockType Property (ADO )
Update Method
get_OLEDBCommand Method
11/13/2018 • 2 minutes to read • Edit Online
Returns the underlying OLE DB Command, first propagating any parameter information set on the ADO
Command to the OLE DB Command.
Syntax
HRESULT get_OLEDBCommand(
IUnknown **ppOLEDBCommand
);
Parameters
ppOLEDBCommand
[out] A pointer to a pointer location where the IUnknown pointer for the underlying OLE DB Command will be
written.
Applies To
IADOCommandConstruction
ActiveCommand Property Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
Cnxn.Open strCnxn
cmd.ActiveConnection = Cnxn
' clean up
Cnxn.Close
Set rst = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rst Is Nothing Then
If rst.State = adStateOpen Then rst.Close
End If
Set rst = Nothing
The ActiveCommandXprint routine is given only a Recordset object, yet it must print the command text and
parameter that created the Recordset. This can be done because the Recordset object's ActiveCommand
property yields the associated Command object.
The Command object's CommandText property yields the parameterized command that created the Recordset.
The Command object's Parameters collection yields the value that was substituted for the command's parameter
placeholder ("?").
Finally, an error message or the author's name and ID are printed.
'BeginActiveCommandPrintVB
Public Sub ActiveCommandXprint(rstp As ADODB.Recordset)
strName = rstp.ActiveCommand.Parameters.Item("LastName").Value
rstp.Close
Set rstp = Nothing
End Sub
'EndActiveCommandPrintVB
See Also
ActiveCommand Property (ADO )
Command Object (ADO )
Recordset Object (ADO )
ActualSize and DefinedSize Properties Example
(JScript)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the ActualSize and DefinedSize properties to display the defined size and actual size of a field.
Cut and paste the following code to Notepad or another text editor, and save it as ActualSizeJS.asp.
<head>
<title>ActualSize and DefinedSize Properties Example (JScript)</title>
<style>
<!--
body {
font-family: 'Verdana','Arial','Helvetica',sans-serif;
BACKGROUND-COLOR:white;
COLOR:black;
}
.thead2 {
background-color: #800000;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
color: white;
}
.tbody {
text-align: center;
background-color: #f7efde;
font-family: 'Verdana','Arial','Helvetica',sans-serif;
font-size: x-small;
}
-->
</style>
</head>
<body bgcolor="White">
try
{
// open connection
Cnxn.Open(strCnxn);
while (!rsSuppliers.EOF)
{
// start a new line
strMessage = '<tr class="tbody">';
// display data
Response.Write(strMessage);
}
// close the table
Response.Write("</table>");
}
catch (e)
{
Response.Write(e.message);
}
finally
{
// clean up
if (rsSuppliers.State == adStateOpen)
rsSuppliers.Close;
if (Cnxn.State == adStateOpen)
Cnxn.Close;
rsSuppliers = null;
Cnxn = null;
}
%>
</body>
</html>
<!-- EndActualSizeJS -->
See Also
ActualSize Property (ADO )
DefinedSize Property
Field Object
ADO Code Examples in Microsoft JScript
10/1/2018 • 2 minutes to read • Edit Online
Use the following code examples to learn how to use the ADO methods, properties, and events when writing in
JScript.
NOTE
Paste the entire code example, from beginning to end, into your code editor. The example may not run correctly if partial
examples are used or if paragraph formatting is lost.
Methods
AddNew Method Example
Append and CreateParameter Methods Example
Execute, Requery, and Clear Methods Example
Find Method Example
GetRows Method Example
Properties
AbsolutePage, PageCount, and PageSize Properties Example
AbsolutePosition and CursorLocation Properties Example
ActiveCommand Property Example
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties
Example
ActualSize and DefinedSize Properties Example
CacheSize Property Example
Filter and RecordCount Properties Example
See Also
ADO Code Examples in Visual Basic
ADO Code Examples VBScript
ADO Code Examples in Visual C++
Appendix D: ADO Samples
StreamTypeEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
These constants do not have ADO/WFC equivalents.
Applies To
Type Property (ADO Stream)
Property Object Properties, Methods, and Events
10/1/2018 • 2 minutes to read • Edit Online
Properties
Attributes Property
Name Property
Type Property
Value Property
Methods
None.
Events
None.
See Also
Property Object (ADO )
SchemaEnum
11/13/2018 • 5 minutes to read • Edit Online
Specifies the type of schema Recordset that the OpenSchema method retrieves.
Remarks
Additional information about the function and columns returned for each ADO constant can be found in topics in
Appendix B: Schema Rowsets of the OLE DB Programmer's Reference. The name of each topic is listed in
parentheses in the Description section of the following table.
Additional information about the function and columns returned for each ADO MD constant can be found in
topics in OLE DB for OLAP Objects and Schema Rowsets in the OLE DB for Online Analytical Processing (OLAP )
documentation. The name of each topic is listed in parentheses in the Description column of the following table.
You can translate the data types of columns in the OLE DB documentation to ADO data types by referring to the
Description column of the ADO DataTypeEnum topic. For example, an OLE DB data type of DBTYPE_WSTR is
equivalent to an ADO data type of adWChar.
ADO generates schema-like results for the constants, adSchemaDBInfoKeywords and
adSchemaDBInfoLiterals. ADO creates a Recordset, and then fills each row with the values returned
respectively by the IDBInfo::GetKeywords and IDBInfo::GetLiteralInfo methods. Additional information about
these methods can be found in the IDBInfo section of the OLE DB Programmer's Reference.
(ASSERTIONS Rowset)
(CATALOGS Rowset)
(CHARACTER_SETS Rowset)
(CHECK_CONSTRAINTS)
Rowset)
CONSTANT VALUE DESCRIPTION CONSTRAINT COLUMNS
(COLLATIONS Rowset)
(COLUMN_PRIVILEGES
Rowset)
(COLUMNS Rowset)
(COLUMN_DOMAIN_USAGE
Rowset)
(CONSTRAINT_COLUMN_US
AGE Rowset)
(CONSTRAINT_TABLE_USAG
E Rowset)
CONSTANT VALUE DESCRIPTION CONSTRAINT COLUMNS
(CUBES Rowset*)
(IDBInfo::GetKeywords)
(IDBInfo::GetLiteralInfo)
(PRIMARY_KEYS Rowset)
(PROVIDER_TYPES Rowset)
(REFERENTIAL_CONSTRAINT
S Rowset)
(SCHEMATA Rowset)
(SQL_LANGUAGES Rowset)
(STATISTICS Rowset)
(TABLE_PRIVILEGES Rowset)
(TABLES Rowset)
(TRANSLATIONS Rowset)
(USAGE_PRIVILEGES Rowset)
(VIEW_COLUMN_USAGE
Rowset)
(VIEWS Rowset)
(VIEW_TABLE_USAGE
Rowset)
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.Schema.ASSERTS
AdoEnums.Schema.CATALOGS
AdoEnums.Schema.CHARACTERSETS
AdoEnums.Schema.CHECKCONSTRAINTS
AdoEnums.Schema.COLLATIONS
AdoEnums.Schema.COLUMNPRIVILEGES
AdoEnums.Schema.COLUMNS
AdoEnums.Schema.COLUMNSDOMAINUSAGE
AdoEnums.Schema.CONSTRAINTCOLUMNUSAGE
AdoEnums.Schema.CONSTRAINTTABLEUSAGE
AdoEnums.Schema.CUBES
AdoEnums.Schema.DBINFOKEYWORDS
AdoEnums.Schema.DBINFOLITERALS
AdoEnums.Schema.DIMENSIONS
AdoEnums.Schema.FOREIGNKEYS
AdoEnums.Schema.HIERARCHIES
AdoEnums.Schema.INDEXES
AdoEnums.Schema.KEYCOLUMNUSAGE
AdoEnums.Schema.LEVELS
AdoEnums.Schema.MEASURES
AdoEnums.Schema.MEMBERS
AdoEnums.Schema.PRIMARYKEYS
AdoEnums.Schema.PROCEDURECOLUMNS
AdoEnums.Schema.PROCEDUREPARAMETERS
AdoEnums.Schema.PROCEDURES
CONSTANT
AdoEnums.Schema.PROPERTIES
AdoEnums.Schema.PROVIDERSPECIFIC
AdoEnums.Schema.PROVIDERTYPES
AdoEnums.Schema.REFERENTIALCONTRAINTS
AdoEnums.Schema.SCHEMATA
AdoEnums.Schema.SQLLANGUAGES
AdoEnums.Schema.STATISTICS
AdoEnums.Schema.TABLECONSTRAINTS
AdoEnums.Schema.TABLEPRIVILEGES
AdoEnums.Schema.TABLES
AdoEnums.Schema.TRANSLATIONS
AdoEnums.Schema.TRUSTEES
AdoEnums.Schema.USAGEPRIVILEGES
AdoEnums.Schema.VIEWCOLUMNUSAGE
AdoEnums.Schema.VIEWS
AdoEnums.Schema.VIEWTABLEUSAGE
Applies To
OpenSchema Method
ConnectPromptEnum
10/1/2018 • 2 minutes to read • Edit Online
Specifies whether a dialog box should be displayed to prompt for missing parameters when opening a connection
to a data source.
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.ConnectPrompt.ALWAYS
AdoEnums.ConnectPrompt.COMPLETE
AdoEnums.ConnectPrompt.COMPLETEREQUIRED
AdoEnums.ConnectPrompt.NEVER
Applies To
Prompt Property-Dynamic (ADO )
Row Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Gets or sets an OLE DB Row object from or on an ADORecordConstruction Interface object. When you use
put_Row to set a Row object, a row is turned into an ADO Record object.
Read/write.Syntax
HRESULT get_Row([out, retval] IUnknown** ppRow);
HRESULT put_Row([in] IUnknown* pRow);
Parameters
ppRow
Pointer to an OLE DB Row object.
PRow
An OLE DB Row object.
Return Values
This property method returns the standard HRESULT values, including S_OK and E_FAIL.
Applies To
ADORecordConstruction Interface
MaxRecords Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the MaxRecords property to limit the number of records that the provider returns from the data source. The
default setting of this property is zero, which means the provider returns all requested records.
The MaxRecords property is read/write when the Recordset is closed and read-only when it is open.
Applies To
Recordset Object (ADO )
See Also
MaxRecords Property Example (VB )
MaxRecords Property Example (VC++)
Precision Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Indicates the degree of precision for numeric values in a Parameter object or for numeric Field objects.
Remarks
Use the Precision property to determine the maximum number of digits used to represent values for a numeric
Parameter or Field object.
The value is read/write on a Parameter object.
For a Fieldobject, Precision is normally read-only. However, for new Field objects that have been appended to
the Fields collection of a Record, Precision is read/write only after the Value property for the Field has been
specified and the data provider has successfully added the new Field by calling the Update method of the Fields
collection.
Applies To
See Also
NumericScale and Precision Properties Example (VB )
NumericScale and Precision Properties Example (VC++)
NumericScale Property (ADO )
Error (Visual C++ Syntax Index with #import)
10/1/2018 • 2 minutes to read • Edit Online
Properties
_bstr_t GetDescription( );
__declspec(property(get=GetDescription)) _bstr_t Description;
long GetHelpContext( );
__declspec(property(get=GetHelpContext)) long HelpContext;
_bstr_t GetHelpFile( );
__declspec(property(get=GetHelpFile)) _bstr_t HelpFile;
long GetNativeError( );
__declspec(property(get=GetNativeError)) long NativeError;
long GetNumber( );
__declspec(property(get=GetNumber)) long Number;
_bstr_t GetSource( );
__declspec(property(get=GetSource)) _bstr_t Source;
_bstr_t GetSQLState( );
__declspec(property(get=GetSQLState)) _bstr_t SQLState;
See Also
Error Object
Delete Method (ADO Recordset)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
recordset.Delete AffectRecords
Parameters
AffectRecords
An AffectEnum value that determines how many records the Delete method will affect. The default value is
adAffectCurrent.
NOTE
adAffectAll and adAffectAllChapters are not valid arguments to Delete.
Remarks
Using the Delete method marks the current record or a group of records in a Recordset object for deletion. If
the Recordset object doesn't allow record deletion, an error occurs. If you are in immediate update mode,
deletions occur in the database immediately. If a record cannot be successfully deleted (due to database
integrity violations, for example), the record will remain in edit mode after the call to Update. This means that
you must cancel the update with CancelUpdate before moving off the current record (for example, with Close,
Move, or NextRecordset).
If you are in batch update mode, the records are marked for deletion from the cache and the actual deletion
happens when you call the UpdateBatch method. Use the Filter property to view the deleted records.
Retrieving field values from the deleted record generates an error. After deleting the current record, the
deleted record remains current until you move to a different record. Once you move away from the deleted
record, it is no longer accessible.
If you nest deletions in a transaction, you can recover deleted records with the RollbackTrans method. If you
are in batch update mode, you can cancel a pending deletion or group of pending deletions with the
CancelBatch method.
If the attempt to delete records fails because of a conflict with the underlying data (for example, a record has
already been deleted by another user), the provider returns warnings to the Errors collection but does not halt
program execution. A run-time error occurs only if there are conflicts on all the requested records.
If the Unique Table dynamic property is set, and the Recordset is the result of executing a JOIN operation on
multiple tables, then the Delete method will only delete rows from the table named in the Unique Table
property.
Applies To
Recordset Object (ADO )
See Also
Delete Method Example (VB )
Delete Method Example (VBScript)
Delete Method Example (VC++)
Delete Method (ADO Fields Collection)
Delete Method (ADO Parameters Collection)
DeleteRecord Method (ADO )
Field Object Properties, Methods, and Events
10/1/2018 • 2 minutes to read • Edit Online
Properties/Collections
ActualSize Property
Attributes Property
DefinedSize Property
Name Property
NumericScale Property
OriginalValue Property
Precision Property
Properties Collection
Status Property (ADO Field)
Type Property
UnderlyingValue Property
Value Property
Methods
AppendChunk Method
GetChunk Method
Events
None.
See Also
Field Object
Properties Collection (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Some ADO objects have a Properties collection made up of Property objects. Each Property object
corresponds to a characteristic of the ADO object specific to the provider.
NOTE
See the Property object topic for a more detailed explanation of how to use Property objects.
The Dynamic Properties of the Recordset object go out of scope (become unavailable) when the
Recordset is closed.
This section contains the following topics.
Properties Collection Properties, Methods, and Events
See Also
Property Object (ADO )
Appendix A: Providers
Index Property
10/1/2018 • 2 minutes to read • Edit Online
Indicates the name of the index currently in effect for a Recordset object.
Remarks
The index named by the Index property must have previously been declared on the base table underlying the
Recordset object. That is, the index must have been declared programmatically either as an ADOX Index object,
or when the base table was created.
A run-time error will occur if the index cannot be set. The Index property cannot be set under the following
conditions:
Within a WillChangeRecordset or RecordsetChangeComplete event handler.
If the Recordset is still executing an operation (which can be determined by the State property).
If a filter has been set on the Recordset with the Filter property.
The Index property can always be set successfully if the Recordset is closed, but the Recordset will not open
successfully, or the index will not be usable, if the underlying provider does not support indexes.
If the index can be set, the current row position may change. This will cause an update to the AbsolutePosition
property, and will fire the WillChangeRecordset, RecordsetChangeComplete, WillMove, and MoveComplete
events.
If the index can be set and the LockType property is adLockPessimistic or adLockOptimistic, then an implicit
UpdateBatch operation is performed. This releases the current and affected groups. Any existing filter is released,
and the current row position is changed to the first row of the reordered Recordset.
The Index property is used in conjunction with the Seek method. If the underlying provider does not support
the Index property, and thus the Seek method, consider using the Find method instead. Determine whether the
Recordset object supports indexes with the Supports(adIndex) method.
The built-in Index property is not related to the dynamic Optimize property, although they both deal with
indexes.
Applies To
Recordset Object (ADO )
See Also
Seek Method and Index Property Example (VB )
Index Object (ADOX)
Seek Method
Error (ADO for Visual C++ Syntax)
10/1/2018 • 2 minutes to read • Edit Online
Properties
get_Description(BSTR *pbstr)
get_NativeError(long *pl)
get_Number(long *pl)
get_Source(BSTR *pbstr)
get_SQLState(BSTR *pbstr)
See Also
Error Object
State Property Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the State property to display a message while asynchronous connections are opening and
asynchronous commands are executing.
// BeginStateCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
// Function declarations
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void StateX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
StateX();
::CoUninitialize();
}
void StateX() {
HRESULT hr = S_OK;
try {
// Open two asynchronous connections,displaying a message while connecting.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
TESTHR(pConnection2.CreateInstance(__uuidof(Connection)));
pCmdRestore->Execute(NULL,NULL,adAsyncExecute);
while(pCmdRestore->State == adStateExecuting)
printf("Restore command executing...\n\n");
}
catch (_com_error &e) {
// Notify the user of errors if any.
PrintProviderError(pConnection);
PrintComError(e);
}
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
if (pConnection2)
if (pConnection2->State == adStateOpen)
pConnection2->Close();
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for (long i = 0 ; i < nCount ; i++) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
See Also
State Property (ADO )
AffectEnum
1/8/2019 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.Affect.ALL
AdoEnums.Affect.ALLCHAPTERS
AdoEnums.Affect.CURRENT
AdoEnums.Affect.GROUP
Applies To
CancelBatch Method (ADO) Delete Method (ADO Recordset)
The WillMove event is called before a pending operation changes the current position in the Recordset. The
MoveComplete event is called after the current position in the Recordset changes.
Syntax
WillMove adReason, adStatus, pRecordset
MoveComplete adReason, pError, adStatus, pRecordset
Parameters
adReason
An EventReasonEnum value that specifies the reason for this event. Its value can be adRsnMoveFirst,
adRsnMoveLast, adRsnMoveNext, adRsnMovePrevious, adRsnMove, or adRsnRequery.
pError
An Error object. It describes the error that occurred if the value of adStatus is adStatusErrorsOccurred;
otherwise the parameter is not set.
adStatus
An EventStatusEnum status value.
When WillMove is called, this parameter is set to adStatusOK if the operation that caused the event was
successful. It is set to adStatusCantDeny if this event cannot request cancellation of the pending operation.
When MoveComplete is called, this parameter is set to adStatusOK if the operation that caused the event was
successful, or to adStatusErrorsOccurred if the operation failed.
Before WillMove returns, set this parameter to adStatusCancel to request cancellation of the pending
operation, or set this parameter to adStatusUnwantedEvent to prevent subsequent notifications.
Before MoveComplete returns, set this parameter to adStatusUnwantedEvent to prevent subsequent
notifications.
pRecordset
A Recordset object. The Recordset for which this event occurred.
Remarks
A WillMove or MoveComplete event may occur due to the following Recordset operations: Open, Move,
MoveFirst, MoveLast, MoveNext, MovePrevious, AddNew, and Requery. These events may occur because of the
following properties: Filter, Index, Bookmark, AbsolutePage, and AbsolutePosition. These events also occur if a
child Recordset has Recordset events connected and the parent Recordset is moved.
You must set the adStatus parameter to adStatusUnwantedEvent for each possible adReason value in order to
completely stop event notification for any event that includes an adReason parameter.
See Also
ADO Events Model Example (VC++)
ADO Event Handler Summary
Recordset Object (ADO )
Status Property Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Status property to display which records have been modified in a batch operation before a
batch update has occurred.
// BeginStatusCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
#include "icrsint.h"
END_ADO_BINDING()
public:
CHAR m_szt_Title_id[7];
ULONG lt_Title_idStatus;
CHAR m_szt_Type[13];
ULONG lt_TypeStatus;
};
// Function declarations
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void StatusX(void);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if(FAILED(CoInitialize(NULL)))
return -1;
StatusX();
::CoUninitialize();
}
void StatusX() {
HRESULT hr = S_OK;
try {
// Open recordset for batch update
TESTHR(hr = pRstTitles.CreateInstance(__uuidof(Recordset)));
pRstTitles->CursorType = adOpenKeyset;
pRstTitles->LockType = adLockBatchOptimistic;
pRstTitles->Open ("titles", strCnn, adOpenKeyset, adLockBatchOptimistic, adCmdTable);
if (pRstTitles)
if (pRstTitles->State == adStateOpen) {
// Cancel the update because this is a demonstration.
pRstTitles->CancelBatch(adAffectAll);
pRstTitles->Close();
}
}
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
See Also
Status Property (ADO Recordset)
OriginalValue and UnderlyingValue Properties
Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example demonstrates the OriginalValue and UnderlyingValue properties by displaying a message if a
record's underlying data has changed during a Recordset batch update.
'BeginOriginalValueVB
Public Sub Main()
On Error GoTo ErrorHandler
' clean up
rstTitles.Close
Cnxn.Close
Set rstTitles = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstTitles Is Nothing Then
If rstTitles.State = adStateOpen Then rstTitles.Close
End If
Set rstTitles = Nothing
See Also
OriginalValue Property (ADO )
Recordset Object (ADO )
UnderlyingValue Property
Delete Method (ADO Parameters Collection)
11/28/2018 • 2 minutes to read • Edit Online
Syntax
Parameters.Delete Index
Parameters
Index
A String value that contains the name of the object you want to delete, or the object's ordinal position (index) in
the collection.
Remarks
Using the Delete method on a collection lets you remove one of the objects in the collection. This method is
available only on the Parameters collection of a Command object. You must use the Parameter object's Name
property or its collection index when calling the Delete method-an object variable is not a valid argument.
Applies To
Parameters Collection (ADO )
See Also
Delete Method (ADO Fields Collection)
Delete Method (ADO Recordset)
DeleteRecord Method (ADO )
GetString Method Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
'BeginGetStringVB
' clean up
rstAuthors.Close
Cnxn.Close
Set rstAuthors = Nothing
Set Cnxn = Nothing
Exit Sub
Exit Sub
ErrorHandler:
' clean up
If Not rstAuthors Is Nothing Then
If rstAuthors.State = adStateOpen Then rstAuthors.Close
End If
Set rstAuthors = Nothing
See Also
GetString Method (ADO )
Recordset Object (ADO )
GetRows Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
array = recordset.GetRows(Rows, Start, Fields )
Return Value
Returns a Variant whose value is a two-dimensional array.
Parameters
Rows
Optional. A GetRowsOptionEnum value that indicates the number of records to retrieve. The default is
adGetRowsRest.
Start
Optional. A String value or Variant that evaluates to the bookmark for the record from which the GetRows
operation should begin. You can also use a BookmarkEnum value.
Fields
Optional. A Variant that represents a single field name or ordinal position, or an array of field names or ordinal
position numbers. ADO returns only the data in these fields.
Remarks
Use the GetRows method to copy records from a Recordset into a two-dimensional array. The first subscript
identifies the field and the second identifies the record number. The array variable is automatically dimensioned
to the correct size when the GetRows method returns the data.
If you do not specify a value for the Rows argument, the GetRows method automatically retrieves all the records
in the Recordset object. If you request more records than are available, GetRows returns only the number of
available records.
If the Recordset object supports bookmarks, you can specify at which record the GetRows method should
begin retrieving data by passing the value of that record's Bookmark property in the Start argument.
If you want to restrict the fields that the GetRows call returns, you can pass either a single field name/number
or an array of field names/numbers in the Fields argument.
After you call GetRows, the next unread record becomes the current record, or the EOF property is set to True if
there are no more records.
Applies To
Recordset Object (ADO )
See Also
GetRows Method Example (VB )
GetRows Method Example (VC++)
Move Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
recordset.Move NumRecords, Start
Parameters
NumRecords
A signed Long expression that specifies the number of records that the current record position moves.
Start
Optional. A String value or Variant that evaluates to a bookmark. You can also use a BookmarkEnum value.
Remarks
The Move method is supported on all Recordset objects.
If the NumRecords argument is greater than zero, the current record position moves forward (toward the end
of the Recordset). If NumRecords is less than zero, the current record position moves backward (toward the
beginning of the Recordset).
If the Move call would move the current record position to a point before the first record, ADO sets the
current record to the position before the first record in the recordset (BOF is True). An attempt to move
backward when the BOF property is already True generates an error.
If the Move call would move the current record position to a point after the last record, ADO sets the current
record to the position after the last record in the recordset (EOF is True). An attempt to move forward when
the EOF property is already True generates an error.
Calling the Move method from an empty Recordset object generates an error.
If you pass the Start argument, the move is relative to the record with this bookmark, assuming the Recordset
object supports bookmarks. If not specified, the move is relative to the current record.
If you are using the CacheSize property to locally cache records from the provider, passing a NumRecords
argument that moves the current record position outside the current group of cached records forces ADO to
retrieve a new group of records, starting from the destination record. The CacheSize property determines the
size of the newly retrieved group, and the destination record is the first record retrieved.
If the Recordset object is forward only, a user can still pass a NumRecords argument less than zero, provided
the destination is within the current set of cached records. If the Move call would move the current record
position to a record before the first cached record, an error will occur. Thus, you can use a record cache that
supports full scrolling over a provider that supports only forward scrolling. Because cached records are loaded
into memory, you should avoid caching more records than are necessary. Even if a forward-only Recordset
object supports backward moves in this way, calling the MovePrevious method on any forward-only
Recordset object will still generate an error.
NOTE
Support for moving backwards in a forward-only Recordset is not predictable, depending upon your provider. If the
current record has been positioned after the last record in the Recordset, Move backwards may not result in the
correct current position.
Applies To
Recordset Object (ADO )
See Also
Move Method Example (VB )
Move Method Example (VBScript)
Move Method Example (VC++)
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods (ADO )
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods (RDS )
MoveRecord Method (ADO )
Supports Method Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Supports method to display the options supported by a recordset opened with different
cursor types. The DisplaySupport procedure is required for this procedure to run.
'BeginSupportsVB
strSQLTitles = "Titles"
rstTitles.Open strSQLTitles, Cnxn, , , adCmdTable
Next intIndex
' clean up
rstTitles.Close
Cnxn.Close
Set rstTitles = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstTitles Is Nothing Then
If rstTitles.State = adStateOpen Then rstTitles.Close
End If
Set rstTitles = Nothing
'BeginSupports2VB
Public Sub DisplaySupport(rstTemp As ADODB.Recordset)
For intIndex = 0 To 10
blnSupports = _
rstTemp.Supports(arrConstants(intIndex))
If blnSupports Then
Select Case arrConstants(intIndex)
Case adAddNew
Debug.Print " AddNew"
Case adApproxPosition
Debug.Print " AbsolutePosition and AbsolutePage"
Case adBookmark
Debug.Print " blnkmark"
Case adDelete
Debug.Print " Delete"
Case adFind
Debug.Print " Find"
Case adHoldRecords
Debug.Print " Holding Records"
Case adMovePrevious
Debug.Print " MovePrevious and Move"
Case adNotify
Debug.Print " Notifications"
Case adResync
Debug.Print " Resyncing data"
Case adUpdate
Case adUpdate
Debug.Print " Update"
Case adUpdateBatch
Debug.Print " batch updating"
End Select
End If
Next intIndex
End Sub
'EndSupports2VB
See Also
Recordset Object (ADO )
Supports Method
Open and Close Methods Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Open and Close methods on both Recordset and Connection objects that have been
opened.
'BeginOpenVB
' clean up
rstEmployees.Close
Cnxn.Close
Set rstEmployees = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstEmployees Is Nothing Then
If rstEmployees.State = adStateOpen Then rstEmployees.Close
End If
Set rstEmployees = Nothing
See Also
Close Method (ADO )
Connection Object (ADO )
Open Method (ADO Connection)
Open Method (ADO Recordset)
Recordset Object (ADO )
Seek Method
10/1/2018 • 2 minutes to read • Edit Online
Searches the index of a Recordset to quickly locate the row that matches the specified values, and changes the
current row position to that row.
Syntax
recordset.Seek KeyValues, SeekOption
Parameters
KeyValues
An array of Variant values. An index consists of one or more columns and the array contains a value to
compare against each corresponding column.
SeekOption
A SeekEnum value that specifies the type of comparison to be made between the columns of the index and the
corresponding KeyValues.
Remarks
Use the Seek method in conjunction with the Index property if the underlying provider supports indexes on the
Recordset object. Use the Supports(adSeek) method to determine whether the underlying provider supports
Seek, and the Supports(adIndex) method to determine whether the provider supports indexes. (For example,
the OLE DB Provider for Microsoft Jet supports Seek and Index.)
If Seek does not find the desired row, no error occurs, and the row is positioned at the end of the Recordset.
Set the Index property to the desired index before executing this method.
This method is supported only with server-side cursors. Seek is not supported when the Recordset object's
CursorLocation property value is adUseClient.
This method can only be used when the Recordset object has been opened with a CommandTypeEnum value
of adCmdTableDirect.
Applies To
Recordset Object (ADO )
See Also
Seek Method and Index Property Example (VB )
Seek Method and Index Property Example (VC++)
Find Method (ADO )
Index Property
Prepared Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the Prepared property to have the provider save a prepared (or compiled) version of the query specified in
the CommandText property before a Command object's first execution. This may slow a command's first
execution, but once the provider compiles a command, the provider will use the compiled version of the
command for any subsequent executions, which will result in improved performance.
If the property is False, the provider will execute the Command object directly without creating a compiled
version.
If the provider does not support command preparation, it may return an error when this property is set to True.
If the provider does not return an error, it simply ignores the request to prepare the command and sets the
Prepared property to False.
Applies To
Command Object (ADO )
See Also
Prepared Property Example (VB )
Prepared Property Example (VC++)
ADO Code Examples in Visual Basic
10/1/2018 • 2 minutes to read • Edit Online
Use the following code examples to learn how to use the ADO methods, properties, and events when writing in
Visual Basic.
NOTE
Paste the entire code example, from Sub to End Sub, into your code editor. The example may not run correctly if partial
examples are used or if paragraph formatting is lost.
Methods
AddNew Method Example
Append and CreateParameter Methods Example
AppendChunk and GetChunk Methods Example
BeginTrans, CommitTrans, and RollbackTrans Methods Example
Cancel Method Example
Clone Method Example
CompareBookmarks Method Example
ConvertToString Method Example
CopyRecord, CopyTo, and SaveToFile Methods Example
CreateRecordset Method Example
Delete Method Example
DeleteRecord and MoveRecord Methods Example
Execute, Requery, and Clear Methods Example
Find Method Example
GetRows Method Example
GetString Method Example
SkipLine Method, EOS, and LineSeparator Properties Example
Move Method Example
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods Example
NextRecordset Method Example
Open and Close Methods Example
OpenSchema Method Example
Read, ReadText, Write, and WriteText Methods Example
Refresh Method Example
Resync Method Example
Save and Open Methods Example
Seek Method and Index Property Example
Supports Method Example
Update and CancelUpdate Methods Example
UpdateBatch and CancelBatch Methods Example
Properties
AbsolutePage, PageCount, and PageSize Properties Example
AbsolutePosition and CursorLocation Properties Example
ActiveCommand Property Example
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties
Example
ActualSize and DefinedSize Properties Example
Attributes and Name Properties Example
BOF, EOF, and Bookmark Properties Example
CacheSize Property Example
ConnectionString, ConnectionTimeout, and State Properties Example
Count Property Example
CursorType, LockType, and EditMode Properties Example
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example
EOS and LineSeparator Properties, SkipLine Method Example
Filter and RecordCount Properties Example
IsolationLevel and Mode Properties Example
Item Property Example
MarshalOptions Property Example
MaxRecords Property Example
NumericScale and Precision Properties Example
Optimize Property Example
OriginalValue and UnderlyingValue Properties Example
Prepared Property Example
Provider and DefaultDatabase Properties Example
Sort Property Example
Source Property Example
State Property Example
Status Property Example
StayInSync Property Example
Type Property Example (Field)
Type Property Example (Property)
Value Property Example
Version Property Example
See Also
ADO Code Examples VBScript
ADO Code Examples in Visual C++
Appendix D: ADO Samples
Provider Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Remarks
Use the Provider property to set or return the name of the provider for a connection. This property can also be
set by the contents of the ConnectionString property or the ConnectionString argument of the Open method;
however, specifying a provider in more than one place while calling the Open method can have unpredictable
results. If no provider is specified, the property will default to MSDASQL (Microsoft OLE DB Provider for
ODBC ).
The Provider property is read/write when the connection is closed and read-only when it is open. The setting
does not take effect until you either open the Connection object or access the Properties collection of the
Connection object. If the setting is not valid, an error occurs.
Applies To
Connection Object (ADO )
See Also
Provider and DefaultDatabase Properties Example (VB )
Provider and DefaultDatabase Properties Example (VB )
Microsoft OLE DB Provider for ODBC
Appendix A: Providers
Move Method Example (VC++)
10/1/2018 • 3 minutes to read • Edit Online
This example uses the Move method to position the record pointer based on user input.
Example
// BeginMoveCpp.cpp
// compile with: /EHsc /c
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <stdio.h>
#include <ole2.h>
#include <stdlib.h>
#include <conio.h>
#include "icrsint.h"
// This Class extracts fname, lname, city and state from the "authors" table.
class CAuthorsRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CAuthorsRs)
public:
char m_au_fname[21];
ULONG lemp_fnameStatus;
char m_au_lname[41];
ULONG lemp_lnameStatus;
char m_au_city[21];
ULONG lemp_cityStatus;
char m_au_state[3];
ULONG lemp_stateStatus;
};
// Function Declaration.
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void MoveX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
if (pstrRet == NULL)
return NULL;
if (!strrchr(strDest, '\n'))
// Exhaust the input buffer.
do {
fgets(strExBuff, sizeof(strExBuff), stdin);
} while (!strrchr(strExBuff, '\n'));
else
// Replace '\n' with '\0'
strDest[strrchr(strDest, '\n') - strDest] = '\0';
return pstrRet;
return pstrRet;
}
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
MoveX();
::CoUninitialize();
}
void MoveX() {
// Define ADO object pointers. Initialize pointers on define. These are in the ADODB:: namespace.
_RecordsetPtr pRstAuthors = NULL;
char *token1;
try {
// Open recordset from Authors table.
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
pRstAuthors->CursorType = adOpenStatic;
// Use client cursor to allow use of AbsolutePosition property.
pRstAuthors->CursorLocation = adUseClient;
pRstAuthors->MoveFirst();
char * strMove;
char strTemp[5];
while (true) {
// Display information about current record and ask how many records to move.
printf("Record %ld of %d\n", pRstAuthors->AbsolutePosition, pRstAuthors->RecordCount);
printf("Author: %s %s\n",
authorsrs.lemp_fnameStatus == adFldOK ?
authorsrs.m_au_fname : "<NULL>",
authorsrs.lemp_lnameStatus == adFldOK ?
authorsrs.m_au_lname : "<NULL>");
printf("Location: %s, %s\n\n",
authorsrs.lemp_cityStatus == adFldOK ?
authorsrs.m_au_city : "<NULL>",
authorsrs.lemp_stateStatus == adFldOK ?
authorsrs.m_au_state : "<NULL>");
// Store bookmark in case the Move goes too far forward or backward.
_variant_t varBookmark = pRstAuthors->Bookmark;
pRstAuthors->Move(lngMove);
if (pRstAuthors->EndOfFile) {
printf("Too far forward! Returning to current record.\n");
pRstAuthors->Bookmark = varBookmark;
}
}
}
catch(_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstAuthors->GetActiveConnection();
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for (long i = 0 ; i < nCount ; i++) {
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number, (LPCSTR) pErr->Description);
}
}
}
Sample Input
1
0
Sample Output
Record 1 of 23
Author: Abraham Bennet
Location: Berkeley, CA
See Also
Move Method (ADO )
ADO Events
1/25/2019 • 2 minutes to read • Edit Online
FieldChangeComplete Called after the value of one or more Field objects has
changed.
See Also
ADO API Reference
ADO Collections
ADO Dynamic Properties
ADO Enumerated Constants
Appendix B: ADO Errors
Handling ADO Events
ADO Methods
ADO Object Model
ADO Objects and Interfaces
ADO Properties
ActiveConnection, CommandText,
CommandTimeout, CommandType, Size, and
Direction Properties Example (VC++)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction
properties to execute a stored procedure.
Example
// BeginActiveConnectionCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <stdio.h>
#include <ole2.h>
#include "conio.h"
#include "icrsint.h"
END_ADO_BINDING()
public:
CHAR m_szau_id[20];
ULONG lau_idStatus;
CHAR m_szau_fname[40];
ULONG lau_fnameStatus;
CHAR m_szau_lname[40];
ULONG lau_lnameStatus;
};
// Function declaration
void ActiveConnectionX();
void PrintProviderError(_ConnectionPtr pConnection);
int main() {
if ( FAILED(::CoInitialize(NULL)) )
return -1;
ActiveConnectionX();
::CoUninitialize();
}
void ActiveConnectionX() {
void ActiveConnectionX() {
HRESULT hr = S_OK;
// Define ADO object pointers, initialize pointers on define. These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
_CommandPtr pCmdByRoyalty = NULL;
_RecordsetPtr pRstByRoyalty = NULL;
_RecordsetPtr pRstAuthors = NULL;
_ParameterPtr pPrmByRoyalty = NULL;
try {
// Define a command object for a stored procedure.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
hr = pConnection->Open(strCnn, "", "", adConnectUnspecified);
TESTHR(pCmdByRoyalty.CreateInstance(__uuidof(Command)));
pCmdByRoyalty->ActiveConnection = pConnection;
pCmdByRoyalty->CommandText = "byRoyalty";
pCmdByRoyalty->CommandType = adCmdStoredProc;
pCmdByRoyalty->CommandTimeout = 15;
TESTHR(pPrmByRoyalty.CreateInstance(__uuidof(Parameter)));
pPrmByRoyalty->Type = adInteger;
pPrmByRoyalty->Size = 3;
pPrmByRoyalty->Direction = adParamInput;
pPrmByRoyalty->Value = vtroyal;
pCmdByRoyalty->Parameters->Append(pPrmByRoyalty);
// Open an IADORecordBinding interface pointer which we'll use for Binding Recordset to a class
TESTHR(pRstAuthors->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));
// Print current data in the recordset ,adding author names from author table.
printf("Authors With %d Percent Royalty", intRoyalty);
while (!(pRstByRoyalty->EndOfFile)) {
strAuthorId = pRstByRoyalty->Fields->Item["au_id"]->Value;
pRstAuthors->Filter = "au_id = '" + strAuthorId + "'";
pRstByRoyalty->MoveNext();
}
}
catch(_com_error &e) {
// Notify the user of errors if any.
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
PrintProviderError(pConnection);
printf("Source : %s \n Description : %s \n", (LPCSTR)bstrSource, (LPCSTR)bstrDescription);
}
if (pRstByRoyalty)
if (pRstByRoyalty->State == adStateOpen)
pRstByRoyalty->Close();
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
if ( (pConnection->Errors->Count) > 0) {
nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for (i = 0 ; i < nCount ; i++) {
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s", pErr->Number, (LPCSTR)pErr->Description);
}
}
}
Input
25
Sample Output
Authors With 25 Percent Royalty
724-80-9391, Stearns MacFeather
899-46-2035, Anne Ringer
See Also
ActiveConnection Property (ADO )
CommandText Property (ADO )
CommandTimeout Property (ADO )
CommandType Property (ADO )
Direction Property
Size Property (ADO Parameter)
Delete Method Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Delete method to remove a specified record from a Recordset.
'BeginDeleteVB
strMsg = strMsg & vbCr & vbCr & "Enter the ID of a record to delete:"
strTitleID = UCase(InputBox(strMsg))
intLoRange = rstRoySched!lorange
intHiRange = rstRoySched!hirange
intHiRange = rstRoySched!hirange
intRoyalty = rstRoySched!royalty
' clean up
rstRoySched.Close
Set rstRoySched = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstRoySched Is Nothing Then
If rstRoySched.State = adStateOpen Then rstRoySched.Close
End If
Set rstRoySched = Nothing
See Also
Delete Method (ADO Recordset)
Recordset Object (ADO )
State Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Indicates for all applicable objects whether the state of the object is open or closed. If the object is executing an
asynchronous method, indicates whether the current state of the object is connecting, executing, or retrieving.
Return Value
Returns a Long value that can be an ObjectStateEnum value. The default value is adStateClosed.
Remarks
You can use the State property to determine the current state of a given object at any time.
The object's State property can have a combination of values. For example, if a statement is executing, this
property will have a combined value of adStateOpen and adStateExecuting.
The State property is read-only.
Applies To
See Also
ConnectionString, ConnectionTimeout, and State Properties Example (VB )
ConnectionString, ConnectionTimeout, and State Properties Example (VC++)
LineSeparator Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Indicates the binary character to be used as the line separator in text Stream objects.
Remarks
LineSeparator is used to interpret lines when reading the content of a text Stream. Lines can be skipped with
the SkipLine method.
LineSeparator is used only with text Stream objects (Type is adTypeText). This property is ignored if Type is
adTypeBinary.
Applies To
Stream Object (ADO )
See Also
Stream Object (ADO )
ADO Properties
1/25/2019 • 5 minutes to read • Edit Online
BOF and EOF BOF indicates that the current record position is before the
first record in a Recordset object.
EOF indicates that the current record position is after the last
record in a Recordset object.
CharSet Indicates the character set into which the contents of a text
Stream should be translated.
DataMember Indicates the name of the data member that will be retrieved
from the object referenced by the DataSource property.
Dialect Indicates the syntax and general rules that the provider will
use to parse the CommandText or CommandStream
properties.
HelpContext and HelpFile Indicates the Help file and topic associated with an Error
object.
Source (ADO Error) Indicates the name of the object or application that originally
generated an error.
Source (ADO Record) Indicates the entity represented by the Record object.
Source (ADO Recordset) Indicates the source for the data in a Recordset object
State Indicates for all applicable objects whether the state of the
object is open or closed. Indicates for all applicable objects
executing an asynchronous method, whether the current
state of the object is connecting, executing, or retrieving
Status (ADO Recordset) Indicates the status of the current record regarding batch
updates or other bulk operations.
Type (ADO Stream) Indicates the type of data that is contained in the Stream
(binary or text).
UnderlyingValue Indicates the current value in the database for a Field object.
See Also
ADO API Reference
ADO Collections
ADO Dynamic Properties
ADO Enumerated Constants
Appendix B: ADO Errors
ADO Events
ADO Methods
ADO Object Model
ADO Objects and Interfaces
SkipLine Method
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Stream.SkipLine
Remarks
All characters up to and including the next line separator are skipped. By default, the LineSeparator is adCRLF. If
you attempt to skip past EOS, the current position will remain at EOS.
The SkipLine method is used with text streams (Type is adTypeText).
Applies To
Stream Object (ADO )
Clear Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Errors.Clear
Remarks
Use the Clear method on the Errors collection to remove all existing Error objects from the collection. When
an error occurs, ADO automatically clears the Errors collection and fills it with Error objects based on the new
error.
Some properties and methods return warnings that appear as Error objects in the Errors collection but do not
halt a program's execution. Before you call the Resync, UpdateBatch, or CancelBatch methods on a Recordset
object; the Open method on a Connection object; or set the Filter property on a Recordset object, call the
Clear method on the Errors collection. That way, you can read the Count property of the Errors collection to
test for returned warnings.
Applies To
Errors Collection (ADO )
See Also
Execute, Requery, and Clear Methods Example (VB )
Execute, Requery, and Clear Methods Example (VBScript)
Execute, Requery, and Clear Methods Example (VC++)
CancelBatch Method (ADO )
Delete Method (ADO Fields Collection)
Delete Method (ADO Parameters Collection)
Delete Method (ADO Recordset)
Filter Property
Resync Method
UpdateBatch Method
GetRows Method Example (VC++)
10/1/2018 • 3 minutes to read • Edit Online
This example uses the GetRows method to retrieve a specified number of rows from a Recordset and to fill an
array with the resulting data. The GetRows method will return less than the desired number of rows in two cases:
either if EOF has been reached, or if GetRows tried to retrieve a record that was deleted by another user. The
function returns False only if the second case occurs. The GetRowsOK function is required for this procedure to
run.
Example
// BeginGetRowsCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <stdio.h>
#include <ole2.h>
#include <conio.h>
// Function Declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void GetRowsX();
bool GetRowsOK(_RecordsetPtr pRstTemp, int intNumber, _variant_t& avarData);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
GetRowsX();
::CoUninitialize();
}
void GetRowsX() {
HRESULT hr = S_OK;
try {
// Open recordset with names and hire dates from employee table.
TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));
if (hr == 0) {
if (intRows > lUbound + 1) {
printf("\n(Not enough records in Recordset to retrieve %d rows)\n", intRows);
}
}
printf("%d record(s) found.\n", lUbound + 1);
if (hr == 0)
printf("%s ",(LPCSTR)(_bstr_t)result);
rgIndices[0] = 1;
if (hr == 0)
printf("%s, ",(LPCSTR)(_bstr_t)result);
rgIndices[0] = 2;
if (hr == 0)
printf("%s\n", (LPCSTR)(_bstr_t)result);
intLines ++;
if (intLines % 10 == 0) {
printf("\nPress any key to continue...");
_getch();
intLines = 0;
system("cls");
}
}
printf("\n");
}
else {
// Assume GetRows error caused by another user's data changes,
// use Requery to refresh the Recordset and start over.
printf("GetRows failed--retry?\n");
char chKey;
do {
chKey = _getch();
} while (toupper(chKey) != 'Y' && toupper(chKey) != 'N');
if (toupper(chKey) == 'Y')
pRstEmployees->Requery(adOptionUnspecified);
else {
printf("GetRows failed!\n");
printf("GetRows failed!\n");
break;
}
}
// Because using GetRows leaves the current record pointer at the last record
// accessed, move the pointer back to the beginning of the Recordset before
// looping back for another search.
pRstEmployees->MoveFirst();
}
}
catch(_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstEmployees->GetActiveConnection();
// Return False only if fewer than the desired number of rows were returned,
// but not because the end of the Recordset was reached.
long lUbound;
HRESULT hr = SafeArrayGetUBound(avarData.parray, 2, &lUbound);
if (hr == 0) {
if ((intNumber > lUbound + 1) && (!(pRstTemp->EndOfFile)))
return false;
else
return true;
}
else {
printf ("\nUnable to Get the Array's Upper Bound\n");
return false;
}
}
Input
2
0
Sample Output
2 record(s) found.
Paolo Accorti, 8/27/1992
Pedro Afonso, 12/24/1990
See Also
BOF, EOF Properties (ADO )
GetRows Method (ADO )
Recordset Object (ADO )
CursorTypeEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT
AdoEnums.CursorType.DYNAMIC
AdoEnums.CursorType.FORWARDONLY
AdoEnums.CursorType.KEYSET
AdoEnums.CursorType.STATIC
AdoEnums.CursorType.UNSPECIFIED
Applies To
CursorType Property (ADO )
Recordset (Visual C++ Syntax Index with #import)
10/1/2018 • 2 minutes to read • Edit Online
Methods
HRESULT AddNew( const _variant_t & FieldList = vtMissing,
const _variant_t & Values = vtMissing );
HRESULT Cancel( );
HRESULT CancelUpdate( );
HRESULT Close( );
HRESULT MoveFirst( );
HRESULT MoveLast( );
HRESULT MoveNext( );
HRESULT MovePrevious( );
Properties
enum PositionEnum GetAbsolutePage( );
void PutAbsolutePage( enum PositionEnum pl );
__declspec(property(get=GetAbsolutePage,put=PutAbsolutePage)) enum
PositionEnum AbsolutePage;
IDispatchPtr GetActiveCommand( );
__declspec(property(get=GetActiveCommand)) IDispatchPtr ActiveCommand;
VARIANT_BOOL GetBOF( );
__declspec(property(get=GetBOF)) VARIANT_BOOL BOF;
_variant_t GetBookmark( );
void PutBookmark( const _variant_t & pvBookmark );
__declspec(property(get=GetBookmark,put=PutBookmark)) _variant_t
Bookmark;
long GetCacheSize( );
void PutCacheSize( long pl );
__declspec(property(get=GetCacheSize,put=PutCacheSize)) long
CacheSize;
_bstr_t GetDataMember( );
void PutDataMember( _bstr_t pbstrDataMember );
__declspec(property(get=GetDataMember,put=PutDataMember)) _bstr_t
DataMember;
IUnknownPtr GetDataSource( );
void PutRefDataSource( IUnknown * ppunkDataSource );
__declspec(property(get=GetDataSource,put=PutRefDataSource)) IUnknownPtr
DataSource;
FieldsPtr GetFields( );
__declspec(property(get=GetFields)) FieldsPtr Fields;
_variant_t GetFilter( );
void PutFilter( const _variant_t & Criteria );
__declspec(property(get=GetFilter,put=PutFilter)) _variant_t Filter;
_bstr_t GetIndex( );
void PutIndex( _bstr_t pbstrIndex );
__declspec(property(get=GetIndex,put=PutIndex)) _bstr_t Index;
long GetMaxRecords( );
void PutMaxRecords( long plMaxRecords );
__declspec(property(get=GetMaxRecords,put=PutMaxRecords)) long
MaxRecords;
long GetPageCount( );
__declspec(property(get=GetPageCount)) long PageCount;
long GetPageSize( );
void PutPageSize( long pl );
__declspec(property(get=GetPageSize,put=PutPageSize)) long PageSize;
long GetRecordCount( );
__declspec(property(get=GetRecordCount)) long RecordCount;
_bstr_t GetSort( );
void PutSort( _bstr_t Criteria );
__declspec(property(get=GetSort,put=PutSort)) _bstr_t Sort;
long GetState( );
__declspec(property(get=GetState)) long State;
long GetStatus( );
__declspec(property(get=GetStatus)) long Status;
VARIANT_BOOL GetStayInSync( );
void PutStayInSync( VARIANT_BOOL pbStayInSync );
__declspec(property(get=GetStayInSync,put=PutStayInSync)) VARIANT_BOOL
StayInSync;
See Also
Recordset Object (ADO )
Status Property Example (Field) (VB)
11/13/2018 • 2 minutes to read • Edit Online
The following example opens a document from a read/write folder using the Internet Publishing Provider. The
Status property of a Field object of the Record will first be set to adFieldPendingInsert, then be updated to
adFieldOk.
'BeginStatusFieldVB
' to integrate this code replace the values in the source string
Sub Main()
File.Fields.Update
' clean up
File.Close
Cnxn.Close
Set File = Nothing
Set Cnxn = Nothing
End Sub
'EndStatusFieldVB
The following example deletes a known Field from a Record opened from a document. The Status property will
first be set to adFieldOK, then adFieldPendingUnknown.
The following code deletes a Field from a Record opened on a read-only document. Status will be set to
adFieldPendingDelete. At Update, the delete will fail and Status will be adFieldPendingDelete plus
adFieldPermissionDenied. CancelUpdate clears the pending Status setting.
See Also
Field Object
Record Object (ADO )
Status Property (ADO Field)
Sort Property Example (VB)
10/1/2018 • 2 minutes to read • Edit Online
This example uses the Recordset object's Sort property to reorder the rows of a Recordset derived from the
Authors table of the Pubs database. A secondary utility routine prints each row.
'BeginSortVB
rstAuthors.MoveFirst
Do Until rstAuthors.EOF
Debug.Print rstAuthors!au_fname & " " & rstAuthors!au_lname
rstAuthors.MoveNext
Loop
Do Until rstAuthors.EOF
Debug.Print rstAuthors!au_fname & " " & rstAuthors!au_lname
rstAuthors.MoveNext
Loop
' clean up
rstAuthors.Close
Cnxn.Close
Set rstAuthors = Nothing
Set rstAuthors = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstAuthors Is Nothing Then
If rstAuthors.State = adStateOpen Then rstAuthors.Close
End If
Set rstAuthors = Nothing
This is the secondary utility routine that prints the given title, and the contents of the specified Recordset.
See Also
Recordset Object (ADO )
Sort Property
GetChunk Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Returns all, or a portion, of the contents of a large text or binary data Field object.
Syntax
variable = field.GetChunk(Size)
Return Value
Returns a Variant.
Parameters
Size
A Long expression that is equal to the number of bytes or characters that you want to retrieve.
Remarks
Use the GetChunk method on a Field object to retrieve part or all of its long binary or character data. In
situations where system memory is limited, you can use the GetChunk method to manipulate long values in
portions, rather than in their entirety.
The data that a GetChunk call returns is assigned to variable. If Size is greater than the remaining data, the
GetChunk method returns only the remaining data without padding variable with empty spaces. If the field is
empty, the GetChunk method returns a null value.
Each subsequent GetChunk call retrieves data starting from where the previous GetChunk call left off.
However, if you are retrieving data from one field and then you set or read the value of another field in the
current record, ADO assumes you have finished retrieving data from the first field. If you call the GetChunk
method on the first field again, ADO interprets the call as a new GetChunk operation and starts reading from
the beginning of the data. Accessing fields in other Recordset objects that are not clones of the first Recordset
object will not disrupt GetChunk operations.
If the adFldLong bit in the Attributes property of a Field object is set to True, you can use the GetChunk
method for that field.
If there is no current record when you use the GetChunk method on a Field object, error 3021 (no current
record) occurs.
NOTE
The GetChunk method does not operate on Field objects of a Record object. It does not perform any operation and will
produce a run-time error.
Applies To
Field Object
See Also
AppendChunk and GetChunk Methods Example (VB )
AppendChunk and GetChunk Methods Example (VC++)
AppendChunk Method (ADO )
Attributes Property (ADO )
ActiveCommand Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Indicates the Command object that created the associated Recordset object.
Return Value
Returns a Variant that contains a Command object. Default is a null object reference.
Remarks
The ActiveCommand property is read-only.
If a Command object was not used to create the current Recordset, then a Null object reference is returned.
Use this property to find the associated Command object when you are given only the resulting Recordset
object.
Applies To
Recordset Object (ADO )
See Also
ActiveCommand Property Example (VB )
ActiveCommand Property Example (JScript)
ActiveCommand Property Example (VC++)
Command Object (ADO )
ADO Syntax Indexes
10/1/2018 • 2 minutes to read • Edit Online
The syntax for calling ADO methods and properties differs depending on your development environment. The rest
of the ADO Language Reference uses the Microsoft Visual Basic programming language to illustrate ADO method
and property syntax. However, refer to the following sections for more specific syntax examples based on your
programming language and methodology:
The ADO for Visual C++ Syntax Index for COM covers ADO properties and methods without using the
#import compiler directive with Microsoft Visual C++.
The ADO for Visual C++ Syntax Index with #import covers ADO properties and methods when using the
#import compiler directive with Microsoft Visual C++.
See Also
Using ADO with Microsoft Visual Basic
Using ADO with Microsoft Visual C++
Using ADO with Scripting Languages
SQLState Property
10/1/2018 • 2 minutes to read • Edit Online
Return Value
Returns a five-character String value that follows the ANSI SQL standard and indicates the error code.
Remarks
Use the SQLState property to read the five-character error code that the provider returns when an error occurs
during the processing of an SQL statement. For example, when using the Microsoft OLE DB Provider for ODBC
with a Microsoft SQL Server database, SQL state error codes originate from ODBC, based either on errors
specific to ODBC or on errors that originate from Microsoft SQL Server, and are then mapped to ODBC errors.
These error codes are documented in the ANSI SQL standard, but may be implemented differently by different
data sources.
Applies To
Error Object
See Also
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VB )
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VC++)
Refresh Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online
Updates the objects in a collection to reflect objects available from, and specific to, the provider.
Syntax
collection.Refresh
Remarks
The Refresh method accomplishes different tasks depending on the collection from which you call it.
Parameters
Using the Refresh method on the Parameters collection of a Command object retrieves provider-side
parameter information for the stored procedure or parameterized query specified in the Command object.
The collection will be empty for providers that do not support stored procedure calls or parameterized queries.
You should set the ActiveConnection property of the Command object to a valid Connection object, the
CommandText property to a valid command, and the CommandType property to adCmdStoredProc before
calling the Refresh method.
If you access the Parameters collection before calling the Refresh method, ADO will automatically call the
method and populate the collection for you.
NOTE
If you use the Refresh method to obtain parameter information from the provider and it returns one or more variable-
length data type Parameter objects, ADO may allocate memory for the parameters based on their maximum potential
size, which will cause an error during execution. You should explicitly set the Size property for these parameters before
calling the Execute method to prevent errors.
Fields
Using the Refresh method on the Fields collection has no visible effect. To retrieve changes from the
underlying database structure, you must use either the Requery method or, if the Recordset object does not
support bookmarks, the MoveFirst method.
Properties
Using the Refresh method on a Properties collection of some objects populates the collection with the
dynamic properties that the provider exposes. These properties provide information about functionality
specific to the provider, beyond the built-in properties ADO supports.
Applies To
Views Collection
See Also
Refresh Method Example (VB )
Refresh Method Example (VC++)
Count Property (ADO )
Refresh Method (RDS )
ADORecordsetConstruction Interface
10/1/2018 • 2 minutes to read • Edit Online
The ADORecordsetConstruction interface is used to construct an ADO Recordset object from an OLE DB
Rowset object in a C/C++ application.
This interface supports the following properties:
Properties
Chapter Read/Write.
Gets/sets an OLE DB Chapter object from/on this ADO
Recordset object.
RowPosition Read/Write.
Gets/sets an OLE DB RowPosition object from/on this ADO
Recordset object.
Rowset Read/Write.
Gets/sets an OLE DB Rowset object from/on this ADO
Recordset object.
Methods
None.
Events
None.
Remarks
Given an OLE DB Rowset object ( pRowset ), the construction of an ADO Recordset object ( adoRs ) amounts to
the following three basic operations:
1. Create an ADO Recordset object:
Recordset20Ptr adoRs;
adoRs.CreateInstance(__uuidof(Recordset));
adoRecordsetConstructionPtr adoRsConstruct=NULL;
adoRs->QueryInterface(__uuidof(ADORecordsetConstruction),
(void**)&adoRsConstruct);
3. Call the IADORecordsetConstruction::put_Rowset property method to set the OLE DB Rowset object on the
ADO Recordset object:
IUnknown *pUnk=NULL;
pRowset->QueryInterface(IID_IUnknown, (void**)&pUnk);
adoRsConstruct->put_Rowset(pUnk);
The resultant adoRs object now represents the ADO Recordset object constructed from the OLE DB Rowset
object.
You can also construct an ADO Recordset object from an OLE DB Chapter or RowPosition object.
Requirements
Version: ADO 2.0 and later
Library: msado15.dll
UUID: 00000283-0000-0010-8000-00AA006D2EA4
See Also
Recordset Object (ADO )
Rowset Property (ADO )
Collections (ADO - WFC Syntax)
10/1/2018 • 2 minutes to read • Edit Online
package com.ms.wfc.data
Parameters
Methods
Properties
Fields
Methods
Properties
Errors
Methods
Properties
This example uses the ActualSize and DefinedSize properties to display the defined size and actual size of a field.
Example
// BeginActualSizeCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include "conio.h"
// Function declarations
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
void ActualSizeX();
void PrintProviderError(_ConnectionPtr pConnection);
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
ActualSizeX();
::CoUninitialize();
}
void ActualSizeX() {
HRESULT hr = S_OK;
try {
// Open a recordset for the stores table.
TESTHR(pRstStores.CreateInstance(__uuidof(Recordset)));
// You have to explicitly pass the Cursor type and LockType to the Recordset here.
hr = pRstStores->Open("stores", strCnn, adOpenForwardOnly, adLockReadOnly, adCmdTable);
// Loop through the recordset displaying the contents of the stor_name field,
// the field's defined size, and its actual size.
pRstStores->MoveFirst();
while (!(pRstStores->EndOfFile)) {
strMessage = "Store Name: ";
strMessage += (_bstr_t)pRstStores->Fields->Item["stor_name"]->Value + "\n";
strMessage += "Defined Size: ";
strMessage += (_bstr_t)pRstStores->Fields->Item["stor_name"]->DefinedSize + "\n";
strMessage += "Actual Size: ";
strMessage += (_bstr_t) pRstStores->Fields->Item["stor_name"]->ActualSize + "\n";
printf("%s\n",(LPCSTR)strMessage);
printf("%s\n",(LPCSTR)strMessage);
pRstStores->MoveNext();
}
}
catch(_com_error &e) {
_variant_t vtConnect = pRstStores->GetActiveConnection();
if ( (pConnection->Errors->Count) > 0) {
nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for (i = 0 ; i < nCount ; i++) {
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number,(LPCSTR ) pErr->Description);
}
}
}
See Also
ActualSize Property (ADO )
DefinedSize Property
Item Property Example (VC++)
10/1/2018 • 3 minutes to read • Edit Online
This example demonstrates how the Item property accesses members of a collection. The example opens the
Authors table of the Pubs database with a parameterized command.
The parameter in the command issued against the database is accessed from the Command object's Parameters
collection by index and name. Then the fields of the returned Recordset are accessed from that object's Fields
collection by index and name.
// BeginItemCpp.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <ole2.h>
#include <stdio.h>
#include <conio.h>
// Function declarations
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void ItemX();
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
int main() {
if (FAILED(::CoInitialize(NULL)))
return -1;
ItemX();
::CoUninitialize();
}
void ItemX() {
HRESULT hr = S_OK;
// Define ADO object pointers. Initialize pointers on define. These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
_RecordsetPtr pRst = NULL;
_CommandPtr pCmd = NULL;
_ParameterPtr pPrm = NULL;
FieldPtr pFld = NULL;
// Other Variables.
_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");
_variant_t Column[9];
_variant_t vIndex;
try {
// Open connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
TESTHR(pRst.CreateInstance(__uuidof(Recordset)));
TESTHR(pCmd.CreateInstance(__uuidof(Command)));
// Set the array with the authors table field (column) names
Column[0] = "au_id";
Column[1] = "au_lname";
Column[2] = "au_fname";
Column[3] = "phone";
Column[4] = "address";
Column[5] = "city";
Column[6] = "state";
Column[6] = "state";
Column[7] = "zip";
Column[8] = "contract";
vIndex = (short) 0;
pPrm = pCmd->Parameters->GetItem(&vIndex);
printf("Parameter name = '%s', value = '%s'\n",
(LPCSTR)pPrm->Name, (LPSTR)(_bstr_t)pPrm->Value);
pFld = pRst->Fields->GetItem(&vIndex);
printf("Field %d : Name = '%s', ", iIndex, (LPCSTR)pFld->GetName());
_variant_t FldVal = pFld->GetValue();
pFld = pRst->Fields->GetItem(Column[iIndex]);
printf("Field name = '%s', ", (LPCSTR)pFld->GetName());
_variant_t FldVal = pFld->GetValue();
See Also
Command Object (ADO )
Fields Collection (ADO )
Item Property (ADO )
Parameters Collection (ADO )
Recordset Object (ADO )
Stream Object (ADO)
10/1/2018 • 2 minutes to read • Edit Online
See Also
Records and Streams
Field (ADO for Visual C++ Syntax)
10/1/2018 • 2 minutes to read • Edit Online
Methods
AppendChunk(VARIANT Data)
GetChunk(long Length, VARIANT *pvar)
Properties
get_ActualSize(long *pl)
get_Attributes(long *pl)
put_Attributes(long lAttributes)
get_DataFormat(IUnknown **ppiDF)
put_DataFormat(IUnknown *piDF)
get_DefinedSize(long *pl)
put_DefinedSize(long lSize)
get_Name(BSTR *pbstr)
get_NumericScale(BYTE *pbNumericScale)
put_NumericScale(BYTE bScale)
get_OriginalValue(VARIANT *pvar)
get_Precision(BYTE *pbPrecision)
put_Precision(BYTE bPrecision)
get_Type(DataTypeEnum *pDataType)
put_Type(DataTypeEnum DataType)
get_UnderlyingValue(VARIANT *pvar)
get_Value(VARIANT *pvar)
put_Value(VARIANT Val)
See Also
Field Object
LineSeparatorsEnum
10/1/2018 • 2 minutes to read • Edit Online
ADO/WFC Equivalent
These constants do not have ADO/WFC equivalents.
Applies To
LineSeparator Property (ADO )
Connection (Visual C++ Syntax Index with #import)
10/1/2018 • 2 minutes to read • Edit Online
Methods
HRESULT Cancel( );
HRESULT Close( );
_RecordsetPtr Execute( _bstr_t CommandText, VARIANT *
RecordsAffected, long Options );
long BeginTrans( );
HRESULT CommitTrans( );
HRESULT RollbackTrans( );
HRESULT Open( _bstr_t ConnectionString, _bstr_t UserID,
_bstr_t Password, long Options );
_RecordsetPtr OpenSchema( enum SchemaEnum Schema, const
_variant_t & Restrictions = vtMissing, const _variant_t &
SchemaID = vtMissing );
Properties
_bstr_t GetConnectionString( );
void PutConnectionString( _bstr_t pbstr );
__declspec(property(get=GetConnectionString,put=PutConnectionString))
_bstr_t ConnectionString;
long GetCommandTimeout( );
void PutCommandTimeout( long plTimeout );
__declspec(property(get=GetCommandTimeout,put=PutCommandTimeout)) long
CommandTimeout;
long GetConnectionTimeout( );
void PutConnectionTimeout( long plTimeout );
__declspec(property(get=GetConnectionTimeout,put=PutConnectionTimeout))
long ConnectionTimeout;
_bstr_t GetVersion( );
__declspec(property(get=GetVersion)) _bstr_t Version;
ErrorsPtr GetErrors( );
__declspec(property(get=GetErrors)) ErrorsPtr Errors;
_bstr_t GetDefaultDatabase( );
void PutDefaultDatabase( _bstr_t pbstr );
__declspec(property(get=GetDefaultDatabase,put=PutDefaultDatabase))
_bstr_t DefaultDatabase;
enum IsolationLevelEnum GetIsolationLevel( );
void PutIsolationLevel( enum IsolationLevelEnum Level );
__declspec(property(get=GetIsolationLevel,put=PutIsolationLevel)) enum
IsolationLevelEnum IsolationLevel;
long GetAttributes( );
void PutAttributes( long plAttr );
__declspec(property(get=GetAttributes,put=PutAttributes)) long
Attributes;
enum CursorLocationEnum GetCursorLocation( );
void PutCursorLocation( enum CursorLocationEnum plCursorLoc );
__declspec(property(get=GetCursorLocation,put=PutCursorLocation)) enum
CursorLocationEnum CursorLocation;
enum ConnectModeEnum GetMode( );
void PutMode( enum ConnectModeEnum plMode );
__declspec(property(get=GetMode,put=PutMode)) enum ConnectModeEnum
Mode;
_bstr_t GetProvider( );
void PutProvider( _bstr_t pbstr );
__declspec(property(get=GetProvider,put=PutProvider)) _bstr_t
Provider;
long GetState( );
__declspec(property(get=GetState)) long State;
See Also
Connection Object (ADO )
Properties Collection Properties, Methods, and
Events
10/1/2018 • 2 minutes to read • Edit Online
Properties
Count Property
Item Property
Methods
Refresh Method
Events
None.
See Also
Properties Collection (ADO )
Execute Method (ADO Connection)
10/1/2018 • 2 minutes to read • Edit Online
Executes the specified query, SQL statement, stored procedure, or provider-specific text.
Syntax
Set recordset = connection.Execute (CommandText, RecordsAffected, Options)
Set recordset = connection.Execute (CommandText, RecordsAffected, Options)
Return Value
Returns a Recordset Object (ADO ) object reference.
Parameters
CommandText
A String value that contains the SQL statement, stored procedure, a URL, or provider-specific text to execute.
Optionally, table names can be used but only if the provider is SQL aware. For example if a table name of
"Customers" is used, ADO will automatically prepend the standard SQL Select syntax to form and pass
"SELECT * FROM Customers" as a Transact-SQL statement to the provider.
RecordsAffected
Optional. A Long variable to which the provider returns the number of records that the operation affected.
Options
Optional. A Long value that indicates how the provider should evaluate the CommandText argument. Can be a
bitmask of one or more CommandTypeEnum or ExecuteOptionEnum values.
Note Use the ExecuteOptionEnum value adExecuteNoRecords to improve performance by minimizing
internal processing and for applications that you are porting from Visual Basic 6.0.
Do not use adExecuteStream with the Execute method of a Connection object.
Do not use the CommandTypeEnum values of adCmdFile or adCmdTableDirect with Execute. These values
can only be used as options with the Open Method (ADO Recordset) and Requery Method methods of a
Recordset.
Remarks
Using the Execute method on a Connection Object (ADO ) object executes whatever query you pass to the
method in the CommandText argument on the specified connection. If the CommandText argument specifies a
row -returning query, any results that the execution generates are stored in a new Recordset object. If the
command is not intended to return results (for example, an SQL UPDATE query) the provider returns
Nothing as long as the option adExecuteNoRecords is specified; otherwise Execute returns a closed
Recordset.
The returned Recordset object is always a read-only, forward-only cursor. If you need a Recordset object with
more functionality, first create a Recordset object with the desired property settings, then use the Recordset
object's Open Method (ADO Recordset) method to execute the query and return the desired cursor type.
The contents of the CommandText argument are specific to the provider and can be standard SQL syntax or
any special command format that the provider supports.
An ExecuteComplete event will be issued when this operation concludes.
NOTE
URLs using the http scheme will automatically invoke the Microsoft OLE DB Provider for Internet Publishing. For more
information, see Absolute and Relative URLs.
Applies To
Connection Object (ADO )
Command Object Properties, Methods, and Events
10/1/2018 • 2 minutes to read • Edit Online
Properties/Collections
ActiveConnection Property
CommandStream Property
CommandText Property
CommandTimeout Property
CommandType Property
Dialect Property
Name Property
NamedParameters Property
Parameters Collection
Prepared Property
Properties Collection
State Property
Methods
Cancel Method
CreateParameter Method
Execute Method (ADO Command)
Events
None.
See Also
Command Object (ADO )
Write Method
10/1/2018 • 2 minutes to read • Edit Online
Syntax
Stream.Write Buffer
Parameters
Buffer
A Variant that contains an array of bytes to be written.
Remarks
Specified bytes are written to the Stream object without any intervening spaces between each byte.
The current Position is set to the byte following the written data. The Write method does not truncate the rest of
the data in a stream. If you want to truncate these bytes, call SetEOS.
If you write past the current EOS position, the Size of the Stream will be increased to contain any new bytes, and
EOS will move to the new last byte in the Stream.
NOTE
The Write method is used with binary streams ( Type is adTypeBinary). For text streams (Type is adTypeText), use
WriteText.
Applies To
Stream Object (ADO )
See Also
WriteText Method
UnderlyingValue Property
10/1/2018 • 2 minutes to read • Edit Online
Return Value
Returns a Variant value that indicates the value of the Field.
Remarks
Use the UnderlyingValue property to return the current field value from the database. The field value in the
UnderlyingValue property is the value that is visible to your transaction and may be the result of a recent
update by another transaction. This may differ from the OriginalValue property, which reflects the value that was
originally returned to the Recordset.
This is similar to using the Resync method, but the UnderlyingValue property returns only the value for a
specific field from the current record. This is the same value that the Resync method uses to replace the Value
property.
When you use this property with the OriginalValue property, you can resolve conflicts that arise from batch
updates.
Record
For Record objects, this property will be empty for fields added before Update is called.
Applies To
Field Object
See Also
OriginalValue and UnderlyingValue Properties Example (VB )
OriginalValue and UnderlyingValue Properties Example (VC++)
OriginalValue Property (ADO )
Resync Method