0% found this document useful (0 votes)
20 views

Adocode

Uploaded by

informatica
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Adocode

Uploaded by

informatica
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 804

Contents

ADO Code Examples


Type Property (ADO Stream)
Prepared Property Example (VC++)
ObjectProxy (ADO - WFC Syntax)
Connection Object Properties, Methods, Events
RecordTypeEnum
MoveRecordOptionsEnum
Refresh Method Example (VB)
CompareBookmarks Method Example (VB)
SeekEnum
ADCPROP_ASYNCTHREADPRIORITY_ENUM
Connection Object (ADO)
Recordset Object (ADO)
Execute, Requery, Clear Example (VB)
Save Method
Begin, Commit, Rollback - TransComplete
EventStatusEnum
PersistFormatEnum
AddNew Method Example (JScript)
CancelUpdate Method (ADO)
Number Property (ADO)
Append Method (ADO)
Execute Method (ADO Command)
CommandStream Property (ADO)
Open and Close Methods Example (VC++)
IsolationLevel Property
ActiveConnection, CommandText, CommandTimeout (JScript)
Filter and RecordCount Properties Example (VB)
XactAttributeEnum
Size Property (ADO Parameter)
PositionEnum
Stream (Visual C++ Syntax Index with import)
PageSize Property (ADO)
Charset Property (ADO)
Prepared Property Example (VB)
Status Property Example (Recordset) (VB)
Item Property (ADO)
Source Property Example (VC++)
CacheSize Property Example (VC++)
Cancel Method (ADO)
FieldStatusEnum
Parameter Object
ADCPROP_AUTORECALC_ENUM
Stream (ADO for Visual C++ Syntax)
Save and Open Methods Example (VB)
AbsolutePage Property (ADO)
WillExecute Event (ADO)
ConnectionEvents (Visual C++ Syntax Index with import)
AddNew Method Example (VBScript)
CancelBatch Method (ADO)
Record Object (ADO)
Version Property (ADO)
ActiveConnection, CommandText, CommandTimeout (VB)
Record Object Properties, Methods, and Events
Position Property (ADO)
Count Property (ADO)
WillConnect Event (ADO)
Provider and DefaultDatabase Properties Example (VC++)
Requery Method
ADO Dynamic Properties
WillChangeRecordset and RecordsetChangeComplete Events (ADO)
Direction Property
BeginTrans, CommitTrans, and RollbackTrans Methods (ADO)
AddNew Method Example (VB)
ResyncEnum
Resync Method Example (VC++)
GetRows Method Example (JScript)
LockTypeEnum
Open Method (ADO Stream)
Unique Table, Unique Schema, Unique Catalog)
ADO Objects and Interfaces
CompareBookmarks Method (ADO)
ADO for Visual C++ Syntax Index for COM
Parameter (ADO - WFC Syntax)
Name Property (ADO)
StreamReadEnum
Command (ADO for Visual C++ Syntax)
Error Object Properties, Methods, and Events
Command (Visual C++ Syntax Index with import)
Update and CancelUpdate Methods Example (VC++)
WillChangeRecord and RecordChangeComplete Events (ADO)
Connection (ADO for Visual C++ Syntax)
Optimize Property Example (VC++)
put_OLEDBCommand Method
CommandType Property (ADO)
ADO Enumerated Constants
ConnectionString, ConnectionTimeout Example (VC++)
ParameterDirectionEnum
AppendChunk Method (ADO)
CommandTimeout Property (ADO)
OriginalValue and UnderlyingValue Example (VC++)
Prompt Property-Dynamic (ADO)
Record (ADO for Visual C++ Syntax)
AbsolutePosition and CursorLocation Example (VB)
DeleteRecord and MoveRecord Example (VB)
AppendChunk and GetChunk Example (VB)
AbsolutePosition and CursorLocation Example (JScript)
ActualSize and DefinedSize Example (VB)
ConnectOptionEnum
ADO API Reference
ReadText Method
FieldEnum
ActiveCommand Property Example (JScript)
StreamWriteEnum
BOF, EOF, and Bookmark Example (VC++)
Recordset (ADO - WFC Syntax)
UpdateBatch and CancelBatch Methods Example (VC++)
ADCPROP_UPDATERESYNC_ENUM
CompareEnum
Find Method Example (VB)
Record (Visual C++ Syntax Index with import)
CopyRecord Method (ADO)
NativeError Property (ADO)
Filter and RecordCount Example (VC++)
RecordsetEvents (Visual C++ Syntax Index with import)
StayInSync Property Example (VB)
BOF, EOF, and Bookmark Properties Example (VB)
CursorType Property (ADO)
PageCount Property (ADO)
ADO Collections
Append and CreateParameter Example (VC++)
CopyTo Method (ADO)
Item Property Example (VB)
GetChildren Method (ADO)
CursorType, LockType,Edit Mode Example (VC++)
Property Object (ADO)
FilterGroupEnum
LoadFromFile Method (ADO)
NextRecordset Method Example (VB)
Field Object
Recordset (ADO for Visual C++ Syntax)
MaxRecords Property Example (VC++)
ADO Code Examples in Visual C++
MarshalOptions Property Example (VB)
GetRowsOptionEnum
Find Method Example (JScript)
Execute, Requery, and Clear Example (VC++)
IDSOShapeExtensions Interface
Clone Method (ADO)
Type Property Example (Field) (VB)
Attributes Property (ADO)
CursorLocationEnum
Resync Method Example (VB)
Open Method (ADO Record)
NextRecordset Method (ADO)
BeginTrans, CommitTrans, and RollbackTrans Example (VB)
AddNew Method (ADO)
MoveFirst, MoveLast, MoveNext, MovePrevious Methods (ADO)
Type Property Example (Property) (VC++)
Optimize Property-Dynamic (ADO)
Size Property (ADO Stream)
MarshalOptions Property Example (VC++)
ADO Methods
FetchComplete Event (ADO)
CacheSize Property Example (VB)
Error (ADO - WFC Syntax)
EditMode Property
Error Object
ADO - WFC Syntax Index
Source Property (ADO Recordset)
Command Object (ADO)
GetRows Method Example (VB)
State Property Example (VB)
RowPosition Property (ADO)
AddNew Method Example (VC++)
NumericScale and Precision Example (VB)
Stream Object Properties, Methods, Events
Stat Method
LockType Property (ADO)
PropertyAttributesEnum
CreateParameter Method (ADO)
DataSpace (ADO - WFC Syntax)
ErrorValueEnum
Flush Method (ADO)
ADOStreamConstruction Interface
IsolationLevel and Mode Example (VC++)
GetString Method (ADO)
MoveFirst, MoveLast, MoveNext Example (VBScript)
Field (Visual C++ Syntax Index with import)
RecordOpenOptionsEnum
IsolationLevelEnum
Connection (ADO - WFC Syntax)
Status Property (ADO Field)
Fields Collection Properties, Methods, Events
NextRecordset Method Example (VC++)
Chapter Property (ADO)
SaveToFile Method
Type Property (ADO)
Update Resync Property-Dynamic (ADO)
ConnectionTimeout Property (ADO)
StreamOpenOptionsEnum
OpenSchema Method
Read Method
RecordCount Property (ADO)
ActiveCommand Property Example (VC++)
SearchDirectionEnum
ADO Dynamic Property Index
Property (Visual C++ Syntax Index with import)
Mode Property (ADO)
Filter Property
MoveFirst, MoveLast, MoveNext, MovePrevious Example (VC++)
ParameterAttributesEnum
Cancel Method Example (VC++)
Field (ADO - WFC Syntax)
EventReasonEnum
Rowset Property (ADO)
Delete Method Example (VC++)
Source Property Example (VB)
Fields Collection (ADO)
Clone Method Example (VC++)
WriteText Method
AbsolutePosition Property (ADO)
RecordType Property (ADO)
ADO Code Examples VBScript
Delete Method Example (VBScript)
EOS and LineSeparator Properties Example (VB)
Parameter (ADO for Visual C++ Syntax)
Resync Method
ActualSize Property (ADO)
Version Property Example (VB)
SetEOS Method
OpenSchema Method Example (VC++)
FieldAttributeEnum
OriginalValue Property (ADO)
Supports Method Example (VC++)
RecordCreateOptionsEnum
MoveRecord Method (ADO)
Parameter (Visual C++ Syntax Index with import)
Update Method
Collections (ADO for Visual C++ Syntax)
Read, ReadText, Write, WriteText Methods Example (VB)
Reshape Name Property-Dynamic (ADO)
ExecuteOptionEnum
Filter and RecordCount Example (JScript)
Provider and DefaultDatabase Example (VB)
Open and Close Methods Example (VBScript)
Open Method (ADO Connection)
Optimize Property Example (VB)
ParentURL Property (ADO)
Clone Method Example (VB)
Parameters Collection Properties, Events
MaxRecords Property Example (VB)
ExecuteComplete Event (ADO)
CopyRecord, CopyTo, and SaveToFile Example (VB)
Errors Collection Properties, Methods, aEvents
ParentRow Property (ADO)
Description, HelpContext, HelpFile, NativeError Example (VB)
Cancel Method Example (VB)
AbsolutePage, PageCount, PageSize Example (VB)
GetDataProviderDSO Method
Find Method Example (VC++)
SaveOptionsEnum
ADO for Visual C++ Syntax Index with import
Sort Property Example (VC++)
EOS Property
Seek Method and Index Property Example (VC++)
ConnectComplete and Disconnect Events (ADO)
Move Method Example (VB)
NumericScale and Precision Properties Example (VC++)
BookmarkEnum
Find Method (ADO)
Update and CancelUpdate Methods Example (VB)
Count Property Example (VC++)
Parameter Object Properties, Methods
Description, HelpContext, HelpFile Example (VC++)
ActiveConnection Property (ADO)
ADORecordConstruction Interface
AppendChunk and GetChunk Methods Example (VC++)
Execute, Requery, and Clear Example (JScript)
RecordStatusEnum
StayInSync Property
Resync Command Property-Dynamic (ADO)
CursorOptionEnum
ConnectionString, ConnectionTimeout Example (VB)
CommandText Property (ADO)
GetString Method Example (VC++)
Description Property
CommandTypeEnum
ADO Object Model
BeginTrans, CommitTrans, and RollbackTrans (VC++)
Stream Property
CacheSize Property (ADO)
Parameters Collection (ADO)
AbsolutePosition and CursorLocation Example (VC++)
Value Property (ADO)
Bookmark Property (ADO)
EndOfRecordset Event (ADO)
Append and CreateParameter Methods Example (VB)
InfoMessage Event (ADO)
EditModeEnum
OpenSchema Method Example (VB)
Type Property Example (Field) (VC++)
Recordset Object Properties, Methods, Events
NamedParameters Property (ADO)
DefaultDatabase Property
Status Property (ADO Recordset)
UpdateBatch and CancelBatch Example (VB)
Source Property (ADO Error)
MarshalOptionsEnum
DefinedSize Property
WillChangeField and FieldChangeComplete Events (ADO)
Refresh Method Example (VC++)
Close Method (ADO)
ConnectionString Property (ADO)
Execute, Requery, and Clear Example (VBScript)
StayInSync Property Example (VC++)
Command (ADO - WFC Syntax)
CursorLocation Property (ADO)
MarshalOptions Property (ADO)
AbsolutePage, PageCount, PageSize Example (VC++)
ConnectModeEnum
Append and CreateParameter Example (JScript)
Collections (Visual C++ Syntax Indeximport)
BOF, EOF Properties (ADO)
Clone Method Example (VBScript)
Sort Property
CacheSize Property Example (JScript)
Count Property Example (VB)
ADCPROP_UPDATECRITERIA_ENUM
IsolationLevel and Mode PExample (VB)
Seek Method and Index Example (VB)
Save and Open Example (VC++)
Dialect Property
ObjectStateEnum
Open Method (ADO Recordset)
MoveFirst, MoveLast, MoveNext Example (VB)
ConvertToString Method Example (VB)
FetchProgress Event (ADO)
DataSource Property (ADO)
CopyRecordOptionsEnum
Type Property Example (Property) (VB)
CreateRecordset Method Example (VB)
Attributes and Name Example (VC++)
AbsolutePage, PageCount, PageSize Example (JScript)
Value Property Example (VB)
CursorType, LockType, EditMode Example (VB)
DataMember Property
DataTypeEnum
Source Property (ADO Record)
HelpContext, HelpFile Properties
Value Property Example (VC++)
Move Method Example (VBScript)
NumericScale Property (ADO)
Supports Method
ADO Events Model Example (VC++)
Errors Collection (ADO)
StringFormatEnum
DeleteRecord Method (ADO)
Delete Method (ADO Fields Collection)
Attributes and Name Properties Example (VB)
CompareBookmarks Method Example (VC++)
Version Property Example (VC++)
UpdateBatch Method
get_OLEDBCommand Method
ActiveCommand Property Example (VB)
ActualSize and DefinedSize Properties Example (JScript)
ADO Code Examples in Microsoft JScript
StreamTypeEnum
Property Object Properties, Methods
SchemaEnum
ConnectPromptEnum
Row Property (ADO)
MaxRecords Property (ADO)
Precision Property (ADO)
Error (Visual C++ Syntax Index with import)
Delete Method (ADO Recordset)
Field Object Properties, Methods Events
Properties Collection (ADO)
Index Property
Error (ADO for Visual C++ Syntax)
State Property Example (VC++)
AffectEnum
WillMove and MoveComplete Events (ADO)
Status Property Example (VC++)
OriginalValue and UnderlyingValue Example (VB)
Delete Method (ADO Parameters Collection)
GetString Method Example (VB)
GetRows Method (ADO)
Move Method (ADO)
Supports Method Example (VB)
Open and Close Methods Example (VB)
Seek Method
Prepared Property (ADO)
ADO Code Examples in Visual Basic
Provider Property (ADO)
Move Method Example (VC++)
ADO Events
ActiveConnection, CommandText Example (VC++)
Delete Method Example (VB)
State Property (ADO)
LineSeparator Property (ADO)
ADO Properties
SkipLine Method
Clear Method (ADO)
GetRows Method Example (VC++)
CursorTypeEnum
Recordset (Visual C++ Syntax Index with import)
Status Property Example (Field) (VB)
Sort Property Example (VB)
GetChunk Method (ADO)
ActiveCommand Property (ADO)
ADO Syntax Indexes
SQLState Property
Refresh Method (ADO)
ADORecordsetConstruction Interface
Collections (ADO - WFC Syntax)
ActualSize and DefinedSize Example (VC++)
Item Property Example (VC++)
Stream Object (ADO)
Field (ADO for Visual C++ Syntax)
LineSeparatorsEnum
Connection (Visual C++ Syntax Index with import)
Properties Collection Properties, Methods, Events
Execute Method (ADO Connection)
Command Object Properties, Methods, Events
Write Method
UnderlyingValue Property
ADO Code Examples
10/1/2018 • 2 minutes to read • Edit Online

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.

ADO Code Examples in Visual Basic


ADO Code Examples in VBScript
ADO Code Examples in Visual C++
ADO Code Examples in JScript
Type Property (ADO Stream)
10/1/2018 • 2 minutes to read • Edit Online

Indicates the type of data contained in the Stream (binary or text).

Settings and Return Values


Sets or returns a StreamTypeEnum value that specifies the type of data contained in the Stream object. The
default value is adTypeText. However, if binary data is initially written to a new, empty Stream, the Type will be
changed to adTypeBinary.

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;

// Define string variables.


_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);

_bstr_t strCmd ("SELECT title,type FROM titles ORDER BY type");

// 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);

// Set a timer,then execute the unprepared command 20 times.


DWORD sngStart = GetTickCount();
for ( int intLoop = 1 ; intLoop <= 20 ; intLoop++ )
pCmd1->Execute(NULL, NULL, adCmdText);

DWORD sngEnd=GetTickCount();
float sngNotPrepared = (float)(sngEnd - sngStart) / (float)1000;

// Reset the timer,then execute the prepared command 20 times


sngStart = GetTickCount();
for ( int intLoop = 1 ; intLoop <= 20 ; intLoop++ )
pCmd2->Execute(NULL, NULL, adCmdText);

sngEnd=GetTickCount();

float sngPrepared = (float)(sngEnd - sngStart) / (float)1000;

// Display performance results


printf("Performance Results:");
printf("\n\nNot Prepared: %6.3f seconds", sngNotPrepared);
printf("\nPrepared: %6.3f seconds", sngPrepared);
}
catch (_com_error &e) {
// Display errors, if any. Pass a connection pointer accessed from the Connection.
PrintProviderError(pConnection);
PrintComError(e);
}

if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print COM errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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

public Object ObjectProxy.( String method )


public Object ObjectProxy.( String method, Object[] args)

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

Specifies the type of Record object.

CONSTANT VALUE DESCRIPTION

adSimpleRecord 0 Indicates a simple record (does not


contain child nodes).

adCollectionRecord 1 Indicates a collection record (contains


child nodes).

adRecordUnknown -1 Indicates that the type of this Record is


unknown.

adStructDoc 2 Indicates a special kind of collection


record that represents COM structured
documents.

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

Specifies the behavior of the Record object MoveRecord method.

CONSTANT VALUE DESCRIPTION

adMoveUnspecified -1 Default. Performs the default move


operation: The operation fails if the
destination file or directory already
exists, and the operation updates
hypertext links.

adMoveOverWrite 1 Overwrites the destination file or


directory, even if it already exists.

adMoveDontUpdateLinks 2 Modifies the default behavior of


MoveRecord method by not updating
the hypertext links of the source
Record. The default behavior depends
on the capabilities of the provider. Move
operation updates links if the provider is
capable. If the provider cannot fix links
or if this value is not specified, then the
move succeeds even when links have
not been fixed.

adMoveAllowEmulation 4 Requests that the provider attempt to


simulate the move (using download,
upload, and delete operations). If the
attempt to move the Record fails
because the destination URL is on a
different server or serviced by a
different provider than the source, this
may cause increased latency or data
loss, due to different provider
capabilities when moving resources
between providers.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection strings

' connection and recordset variables


Dim Cnxn As ADODB.Connection
Dim cmdByRoyalty As ADODB.Command
Dim rstByRoyalty As ADODB.Recordset
Dim rstAuthors As ADODB.Recordset
Dim strCnxn As String
Dim strSQLAuthors As String
' record variables
Dim intRoyalty As Integer
Dim strAuthorID As String
Dim strRoyalty As String

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open a command object for a stored procedure


' with one parameter
Set cmdByRoyalty = New ADODB.Command
Set cmdByRoyalty.ActiveConnection = Cnxn
cmdByRoyalty.CommandText = "byroyalty"
cmdByRoyalty.CommandType = adCmdStoredProc
cmdByRoyalty.Parameters.Refresh

' Get parameter value, execute the command


' and store the results in a recordset
strRoyalty = InputBox("Enter royalty:")
If strRoyalty = "" Then
Err.Raise 1, , "You either didn't enter royalty or canceled the input box. Exit the application"
End If

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

' Print current data in the recordset


' and add author names
Debug.Print "Authors with " & intRoyalty & " percent royalty"

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

If Not rstAuthors Is Nothing Then


If rstAuthors.State = adStateOpen Then rstAuthors.Close
End If
Set rstAuthors = Nothing

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndRefreshVB

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

' recordset and connection variables


Dim rstAuthors As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strSQLAuthors As String
Dim strCnxn As String

' comparison variables


Dim count As Integer
Dim target As Variant
Dim result As Long
Dim strAnswer As String
Dim strTitle As String
strTitle = "CompareBookmarks Example"

' Open a connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open recordset as a static cursor type recordset


Set rstAuthors = New ADODB.Recordset
strSQLAuthors = "SELECT * FROM Authors"
rstAuthors.Open strSQLAuthors, Cnxn, adOpenStatic, adLockReadOnly, adCmdText

count = rstAuthors.RecordCount
Debug.Print "Rows in the Recordset = "; count

' Exit if an empty recordset


If count = 0 Then Exit Sub

' Get position between 0 and count -1


Randomize
count = (Int(count * Rnd))
Debug.Print "Randomly chosen row position = "; count
' Move row to random position
rstAuthors.Move count, adBookmarkFirst
' Remember the mystery row
target = rstAuthors.Bookmark

count = 0
rstAuthors.MoveFirst
' Loop through recordset
Do Until rstAuthors.EOF
Do Until rstAuthors.EOF
result = rstAuthors.CompareBookmarks(rstAuthors.Bookmark, target)

If result = adCompareNotEqual Then


Debug.Print "Row "; count; ": Bookmarks are not equal."
ElseIf result = adCompareNotComparable Then
Debug.Print "Row "; count; ": Bookmarks are not comparable."
Else
Select Case result
Case adCompareLessThan
strAnswer = "less than"
Case adCompareEqual
strAnswer = "equal to"
Case adCompareGreaterThan
strAnswer = "greater than"
Case Else
strAnswer = "in error comparing to"
End Select
'show the results row-by-row
Debug.Print "Row position " & count & " is " & strAnswer & " the target."
End If

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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If

End Sub
'EndCompareBookmarksVB

See Also
CompareBookmarks Method (ADO )
CompareEnum
Recordset Object (ADO )
SeekEnum
10/1/2018 • 2 minutes to read • Edit Online

Specifies the type of Seek to execute.

CONSTANT VALUE DESCRIPTION

adSeekFirstEQ 1 Seeks the first key equal to KeyValues.

adSeekLastEQ 2 Seeks the last key equal to KeyValues.

adSeekAfterEQ 4 Seeks either a key equal to KeyValues


or just after where that match would
have occurred.

adSeekAfter 8 Seeks a key just after where a match


with KeyValues would have occurred.

adSeekBeforeEQ 16 Seeks either a key equal to KeyValuesor


just before where that match would
have occurred.

adSeekBefore 32 Seeks a key just before where a match


with KeyValues would have occurred.

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.

CONSTANT VALUE DESCRIPTION

adPriorityAboveNormal 4 Sets priority between normal and


highest.

adPriorityBelowNormal 2 Sets priority between lowest and


normal.

adPriorityHighest 5 Sets priority to the highest possible.

AdPriorityLowest 1 Sets priority to the lowest possible.

adPriorityNormal 3 Sets priority to normal.

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

Represents an open connection to a data source.

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.

Execute a command as a native method of a Connection


object
To execute a command, give the command a name using the Command object Name property. Set
the ActiveConnection property of the Command object to the connection. Then issue a statement
where the command name is used as if it were a method on the Connection object, followed by
any parameters, and a Recordset object if any rows are returned. Set the Recordset properties to
customize the resulting Recordset. For example:

Dim cnn As New ADODB.Connection


Dim cmd As New ADODB.Command
Dim rst As New ADODB.Recordset
...
cnn.Open "..."
cmd.Name = "yourCommandName"
cmd.ActiveConnection = cnn
...
'Your command name, any parameters, and an optional Recordset.
cnn. "parameter", rst

Execute a stored procedure as a native method of a


Connection object
To execute a stored procedure, issue a statement where the stored procedure name is used as if it
were a method on the Connection object, followed by any parameters. ADO will make a "best
guess" of parameter types. For example:

Dim cnn As New ADODB.Connection


...
'Your stored procedure name and any parameters.
cnn. "parameter"

The Connection object is safe for scripting.


This section contains the following topic.
Connection Object Properties, Methods, and Events

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.

The Mode property governs access permissions.


The Fields collection is the default member of the Recordset object. As a
result, the following two code statements are equivalent.

Debug.Print objRs.Fields.Item(0) ' Both statements print


Debug.Print objRs(0) ' the Value of Item(0).

When a Recordset object is passed across processes, only the rowset


values are marshalled, and the properties of the Recordset object are
ignored. During unmarshalling, the rowset is unpacked into a newly
created Recordset object, which also sets its properties to the default
values.
The Recordset object is safe for scripting.
This section contains the following topic.
Recordset Object Properties, Methods, and Events

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo Err_Execute

' connection, command, and recordset variables


Dim Cnxn As ADODB.Connection
Dim cmdChange As ADODB.Command
Dim rstTitles As ADODB.Recordset
Dim Err As ADODB.Error
Dim strSQLChange As String
Dim strSQLRestore As String
Dim strSQLTitles
Dim strCnxn As String

' Define two SQL statements to execute as command text


strSQLChange = "UPDATE Titles SET Type = 'self_help' WHERE Type = 'psychology'"
strSQLRestore = "UPDATE Titles SET Type = 'psychology' WHERE Type = 'self_help'"

' Open connection


strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Set Cnxn = New ADODB.Connection
Cnxn.Open strCnxn

' Create command object


Set cmdChange = New ADODB.Command
Set cmdChange.ActiveConnection = Cnxn
cmdChange.CommandText = strSQLChange

' Open titles table


Set rstTitles = New ADODB.Recordset
strSQLTitles = "titles"
rstTitles.Open strSQLTitles, Cnxn, , , adCmdTable

' Print report of original data


Debug.Print _
"Data in Titles table before executing the query"
PrintOutput rstTitles

' Call the ExecuteCommand subroutine below to execute cmdChange command


ExecuteCommand cmdChange, rstTitles

' Print report of new data


Debug.Print _
"Data in Titles table after executing the query"
PrintOutput rstTitles
' Use the Connection object's execute method to
' execute SQL statement to restore data and trap for
' errors, checking the Errors collection if necessary
Cnxn.Execute strSQLRestore, , adExecuteNoRecords

' Retrieve the current data by requerying the recordset


rstTitles.Requery

' Print report of restored data using sub from below


Debug.Print "Data after executing the query to restore the original information "
PrintOutput rstTitles

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub

Public Sub ExecuteCommand(cmdTemp As ADODB.Command, rstTemp As ADODB.Recordset)

Dim Err As Error

' Run the specified Command object and trap for


' errors, checking the Errors collection
On Error GoTo Err_Execute
cmdTemp.Execute
On Error GoTo 0

' Retrieve the current data by requerying the recordset


rstTemp.Requery

Exit Sub

Err_Execute:

' Notify user of any errors that result from


' executing the query
If rstTemp.ActiveConnection.Errors.Count > 0 Then
For Each Err In rstTemp.ActiveConnection.Errors
MsgBox "Error number: " & Err.Number & vbCr & _
Err.Description
Next Err
Next Err
End If

Resume Next

End Sub

Public Sub PrintOutput(rstTemp As ADODB.Recordset)

' Enumerate Recordset


Do While Not rstTemp.EOF
Debug.Print " " & rstTemp!Title & _
", " & rstTemp!Type
rstTemp.MoveNext
Loop

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

Saves the Recordset in a file or Stream object.

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:

Dim xDOM As New MSXML.DOMDocument


Dim rsXML As New ADODB.Recordset
Dim sSQL As String, sConn As String

sSQL = "SELECT customerid, companyname, contactname FROM customers"


sConn="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"
rsXML.Open sSQL, sConn
rsXML.Save xDOM, adPersistXML 'Save Recordset directly into a DOM tree.
...

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

Recordset Object (ADO) Stream Object (ADO)

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

Specifies the current status of the execution of an event.

CONSTANT VALUE DESCRIPTION

adStatusCancel 4 Requests cancellation of the operation


that caused the event to occur.

adStatusCantDeny 3 Indicates that the operation cannot


request cancellation of the pending
operation.

adStatusErrorsOccurred 2 Indicates that the operation that


caused the event failed due to an error
or errors.

adStatusOK 1 Indicates that the operation that


caused the event was successful.

adStatusUnwantedEvent 5 Prevents subsequent notifications


before the event method has finished
executing.

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

BeginTransComplete, ConnectComplete and Disconnect EndOfRecordset Event (ADO)


CommitTransComplete, and Events (ADO)
RollbackTransComplete Events (ADO)

ExecuteComplete Event (ADO) FetchComplete Event (ADO) InfoMessage Event (ADO)


WillChangeField and WillChangeRecord and WillChangeRecordset and
FieldChangeComplete Events (ADO) RecordChangeComplete Events (ADO) RecordsetChangeComplete Events
(ADO)

WillConnect Event (ADO) WillExecute Event (ADO) WillMove and MoveComplete Events
(ADO)
PersistFormatEnum
10/1/2018 • 2 minutes to read • Edit Online

Specifies the format in which to save a Recordset.

CONSTANT VALUE DESCRIPTION

adPersistADTG 0 Indicates Microsoft Advanced Data


TableGram (ADTG) format.

adPersistADO 1 Indicates that ADO's own Extensible


Markup Language (XML) format will be
used. This value is the same as
adPersistXML and is included for
backwards compatibility.

adPersistXML 1 Indicates Extensible Markup Language


(XML) format.

adPersistProviderSpecific 2 Indicates that the provider will persist


the Recordset using its own format.

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.

<!-- BeginAddNewJS -->


<%@LANGUAGE="JScript" %>
<!-- Include file for JScript ADO Constants -->
<%// use this meta tag instead of adojavas.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->

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

// open Employee recordset using client-side cursor


rsEmployee.CursorLocation = adUseClient;
rsEmployee.Open("Employees", strCnxn, adOpenKeyset, adLockOptimistic, adCmdTable);

rsEmployee.AddNew();
rsEmployee("FirstName") = FName;
rsEmployee("LastName") = LName;
rsEmployee.Update;

// of course, you would normally do error handling here


Response.Write("New record added.")
}
catch (e)
{
Response.Write(e.message);
Response.Write(e.message);
}
finally
{
// clean up
if (rsEmployee.State == adStateOpen)
rsEmployee.Close;
if (Cnxn.State == adStateOpen)
Cnxn.Close;
rsEmployee = null;
Cnxn = null;
}
}
%>

<form method="post" action="AddNewJS.asp" id=form1 name=form1>


<table>
<tr>
<td colspan="2">
<h4>Please enter the record to add:</h4>
</td>
</tr>
<tr>
<td>
First Name:
</td>
<td>
<input name="FirstName" maxLength=20>
</td>
</tr>
<tr>
<td>
Last Name:
</td>
<td>
<input name="LastName" size="30" maxLength=30>
</td>
</tr>
<tr>
<td align="right">
<input type="submit" value="Submit" name="Submit">
</td>
<TD align="left">
<INPUT type="reset" value="Reset" name="Reset">
</TD>
</tr>
</table>
<INPUT type="hidden" value="AddNew" name="Addit">
</form>
</body>
</HTML>
<!-- EndAddNewJS -->

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

Fields Collection (ADO) Recordset Object (ADO)

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

Indicates the number that uniquely identifies an Error object.

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.

An ExecuteComplete event will be issued when this operation concludes.

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

Indicates the stream used as the input for a Command object.

Settings and Return Values


Sets or returns the stream used as the input for a Command object. The format for this stream is provider-
specific; see your provider's documentation for details. This property is similar to the CommandText property,
which used to specify a string for the input of a Command.

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"

// class extracts only fname,lastname and hire_date from employee table


class CEmployeeRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CEmployeeRs)

// Column fname is the 2nd field in the table


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_sze_fname,
sizeof(m_sze_fname), le_fnameStatus, FALSE)

// Column lname is the 4th field in the table.


ADO_VARIABLE_LENGTH_ENTRY2(4, adVarChar, m_sze_lname,
sizeof(m_sze_lname), le_lnameStatus, FALSE)

// Column hiredate is the 8th field in the table.


ADO_VARIABLE_LENGTH_ENTRY2(8, adDBDate,m_sze_hiredate,
sizeof(m_sze_hiredate), le_hiredateStatus, TRUE)

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';");

IADORecordBinding *picRs = NULL; // Interface Pointer declared.


CEmployeeRs emprs; // C++ Class object
DBDATE varDate;

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

// Open an IADORecordBinding interface pointer for Binding Recordset to a class.


TESTHR(pRstEmployee->QueryInterface(__uuidof(IADORecordBinding),(LPVOID*)&picRs));

// Bind the Recordset to a C++ Class here.


TESTHR(picRs->BindToRecordset(&emprs));

// 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);

// Requery Recordset and reset the hire date.


pRstEmployee->Requery(adOptionUnspecified);

// Open IADORecordBinding interface pointer for Binding Recordset to a class.


TESTHR(pRstEmployee->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Rebind the Recordset to a C++ Class here.


TESTHR(picRs->BindToRecordset(&emprs));
emprs.m_sze_hiredate = varDate;
picRs->Update(&emprs);
printf("\nData after reset\n");
printf("\nData after reset\n");
printf("\tName - Hire Date\n");
printf(" %s %s - %d/%d/%d", 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);
}
catch(_com_error &e) {
// Display errors, if any. Pass a connection pointer accessed from the Connection.
PrintProviderError(pConnection);
PrintComError(e);
}

// Clean up objects before exit.


if (pRstEmployee)
if (pRstEmployee->State == adStateOpen)
pRstEmployee->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print COM errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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

Indicates the level of isolation for a Connection object.

Settings and Return Values


Sets or returns an IsolationLevelEnum value. The default is adXactReadCommitted.

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.

<!-- BeginActiveConnectionJS -->


<%@LANGUAGE="JScript"%>
<%// use this meta tag instead of adojavas.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->

<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

if (iRoyalty > -1)


{
// connection and recordset variables
var Cnxn = Server.CreateObject("ADODB.Connection")
var strCnxn = "Provider='sqloledb';Data Source=" + Request.ServerVariables("SERVER_NAME") + ";" +
"Initial Catalog='pubs';Integrated Security='SSPI';";
var cmdByRoyalty = Server.CreateObject("ADODB.Command");
var cmdByRoyalty = Server.CreateObject("ADODB.Command");
var rsByRoyalty = Server.CreateObject("ADODB.Recordset");
var rsAuthor = Server.CreateObject("ADODB.Recordset");
// display variables
var filter, strMessage;

try
{
// open connection
Cnxn.Open(strCnxn);

cmdByRoyalty.CommandText = "byroyalty";
cmdByRoyalty.CommandType = adCmdStoredProc;
cmdByRoyalty.CommandTimeOut = 15;

// The stored procedure called above is as follows:


// CREATE PROCEDURE byroyalty
// @percentage int
// AS
// SELECT au_id from titleauthor
// WHERE titleauthor.royaltyper = @percentage
// GO

prmByRoyalty = Server.CreateObject("ADODB.Parameter");
prmByRoyalty.Type = adInteger;
prmByRoyalty.Size = 3;
prmByRoyalty.Direction = adParamInput;
prmByRoyalty.Value = iRoyalty;
cmdByRoyalty.Parameters.Append(prmByRoyalty);

cmdByRoyalty.ActiveConnection = Cnxn;

// recordset by Command - Execute


rsByRoyalty = cmdByRoyalty.Execute();

// recordset by Recordset - Open


rsAuthor.Open("Authors", Cnxn);

while (!rsByRoyalty.EOF)
{
// set filter
filter = "au_id='" + rsByRoyalty("au_id")
rsAuthor.Filter = filter + "'";

// start new line


strMessage = "<P>";

// get data
strMessage += rsAuthor("au_fname") + " ";
strMessage += rsAuthor("au_lname") + " ";

// end line
strMessage += "</P>";

// show data
Response.Write(strMessage);

// get next record


rsByRoyalty.MoveNext;
}
}
catch (e)
{
Response.Write(e.message);
}
finally
{
// clean up
if (rsByRoyalty.State == adStateOpen)
rsByRoyalty.Close;
rsByRoyalty.Close;
if (rsAuthor.State == adStateOpen)
rsAuthor.Close;
if (Cnxn.State == adStateOpen)
Cnxn.Close;
rsByRoyalty = null;
rsAuthor = null;
Cnxn = null;
}
}
%>

<hr>

<form method="POST" action="ActiveConnectionJS.asp">


<p align="left">Enter royalty percentage to find (e.g., 40): <input type="text" name="RoyaltyValue"
size="5"></p>
<p align="left"><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2">
</p>
</form>

</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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

' recordset variables


Dim rstPublishers As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim SQLPublishers As String

' criteria variables


Dim intPublisherCount As Integer
Dim strCountry As String
Dim strMessage As String

' open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' open recordset with data from Publishers table


Set rstPublishers = New ADODB.Recordset
SQLPublishers = "publishers"
rstPublishers.Open SQLPublishers, strCnxn, adOpenStatic, , adCmdTable

intPublisherCount = rstPublishers.RecordCount

' get user input


strCountry = Trim(InputBox("Enter a country to filter on (e.g. USA):"))

If strCountry <> "" Then


' open a filtered Recordset object
rstPublishers.Filter = "Country ='" & strCountry & "'"

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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If

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.

Attribute VB_Name = "Filter"

See Also
Filter Property
RecordCount Property (ADO )
Recordset Object (ADO )
XactAttributeEnum
10/1/2018 • 2 minutes to read • Edit Online

Specifies the transaction attributes of a Connection object.

CONSTANT VALUE DESCRIPTION

adXactAbortRetaining 262144 Performs retaining aborts by calling


RollbackTrans to automatically start a
new transaction. Not all providers
support this behavior.

adXactCommitRetaining 131072 Performs retaining commits by calling


CommitTrans to automatically start a
new transaction. Not all providers
support this behavior.

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

Indicates the maximum size, in bytes or characters, of a Parameter object.

Settings and Return Values


Sets or returns a Long value that indicates the maximum size in bytes or characters of a value in a Parameter
object.

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

Specifies the current position of the record pointer within a Recordset.

CONSTANT VALUE DESCRIPTION

adPosBOF -2 Indicates that the current record


pointer is at BOF (that is, the BOF
property is True).

adPosEOF -3 Indicates that the current record


pointer is at EOF (that is, the EOF
property is True).

adPosUnknown -1 Indicates that the Recordset is empty,


the current position is unknown, or the
provider does not support the
AbsolutePage or AbsolutePosition
property.

ADO/WFC Equivalent
Package: com.ms.wfc.data

CONSTANT

AdoEnums.Position.BOF

AdoEnums.Position.EOF

AdoEnums.Position.UNKNOWN

Applies To

AbsolutePage Property (ADO) AbsolutePosition Property (ADO)


Stream (Visual C++ Syntax Index with #import)
10/1/2018 • 2 minutes to read • Edit Online

Methods
HRESULT Cancel( );

HRESULT Close( );

HRESULT CopyTo( struct _Stream * DestStream, int CharNumber );

HRESULT Flush( );

HRESULT LoadFromFile( _bstr_t FileName );

HRESULT Open( const _variant_t & Source, enum


ConnectModeEnum Mode, enum StreamOpenOptionsEnum Options, _bstr_t
UserName, _bstr_t Password );

_variant_t Read( long NumBytes );

_bstr_t ReadText( long NumChars );

HRESULT SaveToFile( _bstr_t FileName, enum SaveOptionsEnum


Options );

HRESULT SetEOS( );

HRESULT SkipLine( );

HRESULT Write( const _variant_t & Buffer );

HRESULT WriteText( _bstr_t Data, enum StreamWriteEnum


Options );

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;

enum LineSeparatorEnum GetLineSeparator( );


void PutLineSeparator( enum LineSeparatorEnum pLS );
__declspec(property(get=GetLineSeparator,put=PutLineSeparator)) enum
LineSeparatorEnum LineSeparator;

enum ConnectModeEnum GetMode( );


void PutMode( enum ConnectModeEnum pMode );
__declspec(property(get=GetMode,put=PutMode)) enum ConnectModeEnum Mode;

long GetPosition( );
void PutPosition( long pPos );
__declspec(property(get=GetPosition,put=PutPosition)) long Position;

long GetSize( );
__declspec(property(get=GetSize)) long Size;

enum ObjectStateEnum GetState( );


__declspec(property(get=GetState)) enum ObjectStateEnum State;

enum StreamTypeEnum GetType( );


void PutType( enum StreamTypeEnum ptype );
__declspec(property(get=GetType,put=PutType)) enum StreamTypeEnum Type;

See Also
Stream Object (ADO )
PageSize Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Indicates how many records constitute one page in the Recordset.

Settings and Return Values


Sets or returns a Long value that indicates how many records are on a page. The default is 10.

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.

Settings and Return Values


Sets or returns a String value that specifies the character set into which the contents of the Stream will be
translated. The default value is Unicode. Allowed values are typical strings passed over the interface as Internet
character set names (for example, "iso-8859-1", "Windows-1252", and so on). For a list of the character set names
that are known by a system, see the subkeys of HKEY_CLASSES_ROOT\MIME\Database\Charset in the
Windows Registry.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

Dim Cnxn As ADODB.Connection


Dim cmd1 As ADODB.Command
Dim cmd2 As ADODB.Command

Dim strCnxn As String


Dim strCmd As String
Dim sngStart As Single
Dim sngEnd As Single
Dim sngNotPrepared As Single
Dim sngPrepared As Single
Dim intLoop As Integer

' Open a connection


strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Set Cnxn = New ADODB.Connection
Cnxn.Open strCnxn

' Create two command objects for the same


' command - one prepared and one not prepared
strCmd = "SELECT title, type FROM Titles ORDER BY type"

Set cmd1 = New ADODB.Command


Set cmd1.ActiveConnection = Cnxn
cmd1.CommandText = strCmd

Set cmd2 = New ADODB.Command


Set cmd2.ActiveConnection = Cnxn
cmd2.CommandText = strCmd
cmd2.Prepared = True

' Set a timer, then execute the unprepared


' command 20 times
sngStart = Timer
For intLoop = 1 To 20
cmd1.Execute
Next intLoop
sngEnd = Timer
sngNotPrepared = sngEnd - sngStart

' Reset the timer, then execute the prepared


' command 20 times
sngStart = Timer
For intLoop = 1 To 20
cmd2.Execute
Next intLoop
sngEnd = Timer
sngEnd = Timer
sngPrepared = sngEnd - sngStart

' Display performance results


MsgBox "Performance Results:" & vbCr & _
" Not Prepared: " & Format(sngNotPrepared, _
"##0.000") & " seconds" & vbCr & _
" Prepared: " & Format(sngPrepared, _
"##0.000") & " seconds"

' clean up
Cnxn.Close
Set Cnxn = Nothing
Set cmd1 = Nothing
Set cmd2 = Nothing
Exit Sub

ErrorHandler:
' clean up
Set cmd1 = Nothing
Set cmd2 = Nothing

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndPreparedVB

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

' connection and recordset variables


Dim rstTitles As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQLTitles As String

' open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' open recordset for batch update


Set rstTitles = New ADODB.Recordset
strSQLTitles = "Titles"
rstTitles.Open strSQLTitles, Cnxn, adOpenKeyset, adLockBatchOptimistic, adCmdTable

' change the type of psychology titles


Do Until rstTitles.EOF
If Trim(rstTitles!Type) = "psychology" Then rstTitles!Type = "self_help"
rstTitles.MoveNext
Loop

' display Title ID and status


rstTitles.MoveFirst
Do Until rstTitles.EOF
If rstTitles.Status = adRecModified Then
Debug.Print rstTitles!title_id & " - Modified"
Else
Debug.Print rstTitles!title_id
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
' Cancel the update because this is a demonstration
rstTitles.CancelBatch
rstTitles.Close
rstTitles.Close
End If
End If
Set rstTitles = Nothing

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndStatusRecordsetVB

See Also
Status Property (ADO Recordset)
Item Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Indicates a specific member of a collection, by name or ordinal number.

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)

Properties Collection (ADO) Tables Collection (ADOX) Users Collection (ADOX)

Views Collection (ADOX)


See Also
Item Property Example (VB )
Item Property Example (VC++)
Source Property Example (VC++)
10/11/2018 • 2 minutes to read • Edit Online

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';");

// Define ADO object pointers. Initialize pointers on define.


// These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
_RecordsetPtr pRstTitles = NULL;
_RecordsetPtr pRstPublishers = NULL;
_RecordsetPtr pRstPublishersDirect = NULL;
_RecordsetPtr pRstTitlesPublishers = NULL;
_CommandPtr pCmdSQL = NULL;

try {
// Open a connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open (strCnn, "", "", adConnectUnspecified);

// Open a recordset based on a command object.


TESTHR(pCmdSQL.CreateInstance(__uuidof(Command)));
pCmdSQL->ActiveConnection = pConnection;
pCmdSQL->CommandText = strCmdSQL;
pRstTitles = pCmdSQL->Execute(NULL, NULL, adCmdText);

// Open a recordset based on a table


TESTHR(pRstPublishers.CreateInstance(__uuidof(Recordset)));
pRstPublishers->Open ("publishers", _variant_t((IDispatch *) pConnection, true),
pRstPublishers->Open ("publishers", _variant_t((IDispatch *) pConnection, true),
adOpenForwardOnly, adLockReadOnly, adCmdTable);

// Open a recordset based on a table


TESTHR(pRstPublishersDirect.CreateInstance(__uuidof(Recordset)));
pRstPublishersDirect->Open ("publishers", _variant_t((IDispatch *) pConnection, true),
adOpenForwardOnly, adLockReadOnly, adCmdTableDirect);

// Open a recordset based on a SQL string.


TESTHR(pRstTitlesPublishers.CreateInstance(__uuidof(Recordset)));
pRstTitlesPublishers->Open(strSQL, _variant_t((IDispatch *) pConnection, true),
adOpenForwardOnly, adLockReadOnly, adCmdText);

// Use the Source property to display the source of each recordset.


printf("rstTitles source: \n%s\n\n",
(LPCSTR)(_bstr_t) pRstTitles->GetSource().bstrVal);

printf("rstPublishers source: \n%s\n\n",


(LPCSTR)(_bstr_t) pRstPublishers->GetSource().bstrVal);

printf("rstPublishersDirect source: \n%s\n\n",


(LPCSTR)(_bstr_t) pRstPublishersDirect->GetSource().bstrVal);

printf("rstTitlesPublishers source: \n%s\n\n",


(LPCSTR)(_bstr_t) pRstTitlesPublishers->GetSource().bstrVal);
}
catch (_com_error &e) {
// Notify the user of errors if any.
PrintProviderError(pConnection);
PrintComError(e);
}

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();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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;

// Define Other Variables


DWORD sngStart;
DWORD sngEnd;
float sngNoCache;
float sngCache;
int intLoop = 0;
_bstr_t strTemp;

_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated


Security='SSPI';");

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();

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();
sngNoCache = (float)(sngEnd - sngStart) / (float)1000;

// Cache records in groups of 30 records.


pRstRoySched->MoveFirst();
pRstRoySched->CacheSize = 30;

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;

// Display performance results.


printf("Caching Performance Results:\n");
printf("No cache: %6.3f seconds \n", sngNoCache);
printf("30-record cache: %6.3f seconds", sngCache);
}
catch(_com_error &e) {
// Notify the user of errors if any.
_variant_t vtConnect = pRstRoySched->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:
// Pass a connection pointer accessed from the Recordset.
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}

// Clean up objects before exit.


if (pRstRoySched)
if (pRstRoySched->State == adStateOpen)
pRstRoySched->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

See Also
CacheSize Property (ADO )
Recordset Object (ADO )
Cancel Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Cancels execution of a pending asynchronous method call.

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.

THE LAST ASYNCHRONOUS CALL TO THIS METHOD IS


IF OBJECT IS A TERMINATED

Command Execute

Connection Execute or Open

Record CopyRecord, DeleteRecord, MoveRecord, or Open

Recordset Open

Stream Open

Applies To

Command Object (ADO) Connection Object (ADO) Record Object (ADO)

Recordset Object (ADO) Stream Object (ADO)

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

Specifies the status of a Field Object.


The adFieldPending* values indicate the operation that caused the status to be set, and may be combined with
other status values.

CONSTANT VALUE DESCRIPTION

adFieldAlreadyExists 26 Indicates that the specified field already


exists.

adFieldBadStatus 12 Indicates that an invalid status value


was sent from ADO to the OLE DB
provider. Possible causes include an OLE
DB 1.0 or 1.1 provider, or an improper
combination of Value and Status.

adFieldCannotComplete 20 Indicates that the server of the URL


specified by Source could not complete
the operation.

adFieldCannotDeleteSource 23 Indicates that during a move operation,


a tree or subtree was moved to a new
location, but the source could not be
deleted.

adFieldCantConvertValue 2 Indicates that the field cannot be


retrieved or stored without loss of data.

adFieldCantCreate 7 Indicates that the field could not be


added because the provider exceeded a
limitation (such as the number of fields
allowed).

adFieldDataOverflow 6 Indicates that the data returned from


the provider overflowed the data type
of the field.

adFieldDefault 13 Indicates that the default value for the


field was used when setting data.

adFieldDoesNotExist 16 Indicates that the field specified does


not exist.

adFieldIgnore 15 Indicates that this field was skipped


when setting data values in the source.
The provider set no value.

adFieldIntegrityViolation 10 Indicates that the field cannot be


modified because it is a calculated or
derived entity.
CONSTANT VALUE DESCRIPTION

adFieldInvalidURL 17 Indicates that the data source URL


contains invalid characters.

adFieldIsNull 3 Indicates that the provider returned a


VARIANT value of type VT_NULL and
that the field is not empty.

adFieldOK 0 Default. Indicates that the field was


successfully added or deleted.

adFieldOutOfSpace 22 Indicates that the provider is unable to


obtain enough storage space to
complete a move or copy operation.

adFieldPendingChange 0x40000 Indicates either that the field has been


deleted and then re-added, perhaps
with a different data type, or that the
value of the field which previously had a
status of adFieldOK has changed. The
final form of the field will modify the
Fields collection after the Update
method is called.

adFieldPendingDelete 0x20000 Indicates that the Delete operation


caused the status to be set. The field
has been marked for deletion from the
Fields collection after the Update
method is called.

adFieldPendingInsert 0x10000 Indicates that the Append operation


caused the status to be set. The Field
has been marked to be added to the
Fields collection after the Update
method is called.

adFieldPendingUnknown 0x80000 Indicates that the provider cannot


determine what operation caused field
status to be set.

adFieldPendingUnknownDelete 0x100000 Indicates that the provider cannot


determine what operation caused field
status to be set, and that the field will
be deleted from the Fields collection
after the Update method is called.

adFieldPermissionDenied 9 Indicates that the field cannot be


modified because it is defined as read-
only.

adFieldReadOnly 24 Indicates that the field in the data


source is defined as read-only.
CONSTANT VALUE DESCRIPTION

adFieldResourceExists 19 Indicates that the provider was unable


to perform the operation because an
object already exists at the destination
URL and it is not able to overwrite the
object.

adFieldResourceLocked 18 Indicates that the provider was unable


to perform the operation because the
data source is locked by one or more
other application or process.

adFieldResourceOutOfScope 25 Indicates that a source or destination


URL is outside the scope of the current
record.

adFieldSchemaViolation 11 Indicates that the value violated the


data source schema constraint for the
field.

adFieldSignMismatch 5 Indicates that data value returned by


the provider was signed but the data
type of the ADO field value was
unsigned.

adFieldTruncated 4 Indicates that variable-length data was


truncated when reading from the data
source.

adFieldUnavailable 8 Indicates that the provider could not


determine the value when reading from
the data source. For example, the row
was just created, the default value for
the column was not available, and a
new value had not yet been specified.

adFieldVolumeNotFound 21 Indicates that the provider is unable to


locate the storage volume indicated by
the URL.

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.

CONSTANT VALUE DESCRIPTION

adRecalcAlways 1 Default. Recalculates whenever the


MSDataShape provider determines
values that the calculated columns
depend upon have changed.

adRecalcUpFront 0 Calculates only when initially building


the hierarchical Recordset.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

'recordset and connection variables


Dim rstAuthors As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQLAuthors As String

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

Set rstAuthors = New ADODB.Recordset


strSQLAuthors = "SELECT au_id, au_lname, au_fname, city, phone FROM Authors"
rstAuthors.Open strSQLAuthors, Cnxn, adOpenDynamic, adLockOptimistic, adCmdText

'For sake of illustration, save the Recordset to a diskette in XML format


rstAuthors.Save "c:\Pubs.xml", adPersistXML

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndSaveVB

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.

Attribute VB_Name = "Save"

Finally, you return home. Now update the database with your changes.

Attribute VB_Name = "Save"


See Also
Open Method (ADO Recordset)
Recordset Object (ADO )
More About Recordset Persistence
Save Method
AbsolutePage Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Indicates on which page the current record resides.

Settings and Return Values


For 32-bit code, sets or returns a Long value from 1 to the number of pages in the Recordset object
(PageCount), or returns one of the PositionEnum values.
For 64-bit code, use a data type that provides for storage of a 64-bit value. For example, you can use either
Long or another value that can be 64-bit length such as DBORDINAL. Do not use PositionEnum values
because they are limited to 32-bit length.

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

HRESULT BeginTransComplete( long TransactionLevel,


struct Error * pError, enum EventStatusEnum * adStatus, struct
_Connection * pConnection );

HRESULT CommitTransComplete( struct Error *


pError, enum EventStatusEnum * adStatus, struct _Connection *
pConnection );

HRESULT RollbackTransComplete( struct Error *


pError, enum EventStatusEnum * adStatus, struct _Connection *
pConnection );

HRESULT WillExecute( BSTR * Source, enum


CursorTypeEnum * CursorType,
enum LockTypeEnum * LockType, long * Options, enum EventStatusEnum *
adStatus, struct _Command * pCommand, struct _Recordset * pRecordset,
struct _Connection * pConnection );

HRESULT ExecuteComplete( long RecordsAffected, struct


Error * pError, enum EventStatusEnum * adStatus, struct _Command
* pCommand, struct _Recordset * pRecordset, struct _Connection *
pConnection );

HRESULT WillConnect( BSTR * ConnectionString, BSTR *


UserID, BSTR * Password, long * Options, enum EventStatusEnum *
adStatus, struct _Connection * pConnection );

HRESULT ConnectComplete( struct Error *


pError, enum EventStatusEnum * adStatus, struct _Connection *
pConnection );

HRESULT Disconnect( enum EventStatusEnum *


adStatus, struct _Connection * pConnection );
AddNew Method Example (VBScript)
10/1/2018 • 2 minutes to read • Edit Online

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.

<!-- BeginAddNewVBS -->


<%@Language = VBScript %>
<%' use this meta tag instead of adovbs.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->
<HTML>
<HEAD>
<TITLE>ADO AddNew Method (VBScript)</TITLE>
<STYLE>
<!--
body {
font-family: 'Verdana','Arial','Helvetica',sans-serif;
BACKGROUND-COLOR:white;
COLOR:black;
}
TH {
background-color: #008080;
font-family: 'Arial Narrow','Arial',sans-serif;
font-size: xx-small;
color: white;
}
TD {
text-align: center;
background-color: #f7efde;
font-family: 'Arial Narrow','Arial',sans-serif;
font-size: xx-small;
}
-->
</STYLE>
</HEAD>
<BODY>

<H1>ADO AddNew Method (VBScript)</H1>

<% ' to integrate/test this code replace the


' Data Source value in the Connection string%>
<%
' connection and recordset variables
Dim Cnxn, strCnxn
Dim rsCustomers, strSQLCustomers
Dim fld, Err

' open connection


Set Cnxn = Server.CreateObject("ADODB.Connection")
strCnxn = "Provider='sqloledb';Data Source=" & _
Request.ServerVariables("SERVER_NAME") & ";" & _
"Integrated Security='SSPI';Initial Catalog='Northwind';"
Cnxn.Open strCnxn

' create and open Recordset using object refs


Set rsCustomers = Server.CreateObject("ADODB.Recordset")
strSQLCustomers = "Customers"

rsCustomers.ActiveConnection = Cnxn
rsCustomers.CursorLocation = adUseClient
rsCustomers.CursorType = adOpenKeyset
rsCustomers.LockType = adLockOptimistic
rsCustomers.Source = strSQLCustomers
rsCustomers.Open

'If this is first time page is open, Form collection


'will be empty when data is entered. run AddNew method
If Not IsEmpty(Request.Form) Then
If Not Request.Form("CompanyName") = "" Then
rsCustomers.AddNew
rsCustomers("CustomerID") = Request.Form("CompanyID")
rsCustomers("CompanyName") = Request.Form("CompanyName")
rsCustomers("ContactName") = Request.Form("FirstName") & _
" " & Request.Form("LastName")
rsCustomers("Phone") = Request.Form("PhoneNumber")
rsCustomers("City") = Request.Form("City")
rsCustomers("Region") = Request.Form("State")
rsCustomers.Update
' check for errors
If Cnxn.Errors.Count > 0 Then
For Each Err In Cnxn.Errors
Response.Write("Error " & Err.SQLState & ": " & _
Err.Description & " | " & Err.NativeError)
Next
Cnxn.Errors.Clear
rsCustomers.CancelUpdate
End If
'On Error GoTo 0
rsCustomers.MoveFirst
End If
End If
%>

<TABLE COLSPAN="8" CELLPADDING=5 BORDER=1 ALIGN="center">


<!-- BEGIN column header row for Customer Table-->
<TR>
<TH>Customer ID</TH>
<TH>Company Name</TH>
<TH>Contact Name</TH>
<TH>Phone Number</TH>
<TH>City</TH>
<TH>State/Province</TH>
</TR>

<% ' show the data


Do Until rsCustomers.EOF
Response.Write("<TR>")
Response.Write("<TD>" & rsCustomers("CustomerID") & "</TD>")
Response.Write("<TD>" & rsCustomers("CompanyName")& "</TD>")
Response.Write("<TD>" & rsCustomers("ContactName") & "</TD>")
Response.Write("<TD>" & rsCustomers("Phone") & "</TD>")
Response.Write("<TD>" & rsCustomers("City") & "</TD>")
Response.Write("<TD>" & rsCustomers("Region") & "</TD>")
Response.Write("</TR>")
rsCustomers.MoveNext
Loop
%>
</TABLE>

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

' Clean up.


If rsCustomers.State = adStateOpen then
rsCustomers.Close
End If
If Cnxn.State = adStateOpen then
Cnxn.Close
End If
Set rsCustomers=Nothing
Set Cnxn=Nothing
Set fld=Nothing
%>

<SCRIPT Language = "VBScript">


Sub Form_OnSubmit
MsgBox "Sending New Record to Server",,"ADO-ASP _Example"
End Sub
</SCRIPT>
</BODY>
</HTML>
<!-- EndAddNewVBS -->

See Also
AddNew Method (ADO )
Recordset Object (ADO )
CancelBatch Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Cancels a pending batch update.

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

Indicates the ADO version number.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

'recordset, command and connection variables


Dim Cnxn As ADODB.Connection
Dim cmdByRoyalty As ADODB.Command
Dim prmByRoyalty As ADODB.Parameter
Dim rstByRoyalty As ADODB.Recordset
Dim rstAuthors As ADODB.Recordset
Dim strCnxn As String
Dim strSQLAuthors As String
Dim strSQLByRoyalty As String
'record variables
Dim intRoyalty As Integer
Dim strAuthorID As String

' Define a command object for a stored procedure


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

Set cmdByRoyalty = New ADODB.Command


Set cmdByRoyalty.ActiveConnection = Cnxn
' Set the criteria
strSQLByRoyalty = "byroyalty"
cmdByRoyalty.CommandText = strSQLByRoyalty
cmdByRoyalty.CommandType = adCmdStoredProc
cmdByRoyalty.CommandTimeout = 15

' Define the stored procedure's input parameter


intRoyalty = Trim(InputBox("Enter royalty:"))
Set prmByRoyalty = New ADODB.Parameter
prmByRoyalty.Type = adInteger
prmByRoyalty.Size = 3
prmByRoyalty.Direction = adParamInput
prmByRoyalty.Value = intRoyalty

cmdByRoyalty.Parameters.Append prmByRoyalty

' Create a recordset by executing the command.


Set rstByRoyalty = cmdByRoyalty.Execute()

' Open the Authors Table to get author names for display
Set rstAuthors = New ADODB.Recordset
strSQLAuthors = "Authors"

'rstAuthors.Open strSQLAuthors, strCnxn, , , adCmdTable


rstAuthors.Open strSQLAuthors, strCnxn, adOpenForwardOnly, adLockReadOnly, adCmdTable
'the above two lines of code are identical as the default values for
'CursorType and LockType arguments match those shown

' 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

If Not rstByRoyalty Is Nothing Then


If rstByRoyalty.State = adStateOpen Then rstByRoyalty.Close
End If
Set rstByRoyalty = Nothing

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndActiveConnectionVB

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

Indicates the current position within a Stream object.

Settings and Return Values


Sets or returns a Long value that specifies the offset, in number of bytes, of the current position from the
beginning of the stream. The default is 0, which represents the first byte in the stream.

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

Indicates the number of objects in a collection.

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)

Properties Collection (ADO) Tables Collection (ADOX) Users Collection (ADOX)

Views 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

The WillConnect event is called before a connection starts.


Applies To: Connection Object (ADO )

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

// Open a connection using the OLE DB Provider for Microsoft Jet.


TESTHR(pConnection2.CreateInstance(__uuidof(Connection)));
pConnection2->Provider = "Microsoft.Jet.OLEDB.4.0";

char *sConn = "c:\\Northwind.mdb";


pConnection2->Open(sConn, "admin", "", NULL);
// Display the provider
printf("Connection2 provider: %s \n\n",(LPCSTR)pConnection2->Provider);

// Requires SQL Server authentication


// Open a Connection using the Microsoft SQL Server provider.
TESTHR(pConnection3.CreateInstance(__uuidof(Connection)));
pConnection3->Provider = "sqloledb";
pConnection3->Open("Data Source='(local)';Initial Catalog='pubs';Integrated Security=SSPI", "", "",
NULL);
// Display the provider.
printf("Connection3 provider: %s\n\n", (LPCSTR)pConnection3->Provider);
}
catch (_com_error &e) {
// Notify the user of errors if any.
PrintProviderError(pConnection1);
if (pConnection2)
PrintProviderError(pConnection2);

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();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print COM errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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.

Optimize Specifies whether an index should be created on this field.

Prompt Specifies whether the OLE DB provider should prompt the


user for initialization information.

Reshape Name Specifies a name for the Recordset object.

Resync Command 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.

Unique Table, Unique Schema, Unique Catalog 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 that contains the table.

Update Resync Specifies whether the UpdateBatch method is followed by an


implicit Resync method operation, and if so, the scope of that
operation.

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.

Settings and Return Values


Sets or returns a ParameterDirectionEnum value.

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.

Remote Data Service


The BeginTrans, CommitTrans, and RollbackTrans methods are not available on a client-side Connection
object.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

'recordset and connection variables


Dim Cnxn As ADODB.Connection
Dim rstEmployees As ADODB.Recordset
Dim strCnxn As String
Dim strSQL As String
'record variables
Dim strID As String
Dim strFirstName As String
Dim strLastName As String
Dim blnRecordAdded As Boolean

' Open a connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Northwind';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open Employees Table with a cursor that allows updates


Set rstEmployees = New ADODB.Recordset
strSQL = "Employees"
rstEmployees.Open strSQL, strCnxn, adOpenKeyset, adLockOptimistic, adCmdTable

' Get data from the user


strFirstName = Trim(InputBox("Enter first name:"))
strLastName = Trim(InputBox("Enter last name:"))

' Proceed only if the user actually entered something


' for both the first and last names
If strFirstName <> "" And strLastName <> "" Then

rstEmployees.AddNew
rstEmployees!firstname = strFirstName
rstEmployees!LastName = strLastName
rstEmployees.Update
blnRecordAdded = True

' Show the newly added data


MsgBox "New record: " & rstEmployees!EmployeeId & " " & _
rstEmployees!firstname & " " & rstEmployees!LastName

Else
MsgBox "Please enter a first name and last name."
End If

' Delete the new record because this is a demonstration


Cnxn.Execute "DELETE FROM Employees WHERE EmployeeID = '" & strID & "'"

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndAddNewVB

See Also
AddNew Method (ADO )
Recordset Object (ADO )
ResyncEnum
10/1/2018 • 2 minutes to read • Edit Online

Specifies whether underlying values are overwritten by a call to Resync.

CONSTANT VALUE DESCRIPTION

adResyncAllValues 2 Default. Overwrites data, and pending


updates are canceled.

adResyncUnderlyingValues 1 Does not overwrite data, and pending


updates are not canceled.

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';");

// Define ADO object pointers. Initialize pointers on define.


// These are in the ADODB:: namespace.
_RecordsetPtr pRstTitles = NULL;

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

// Change the type of the first title in the recordset.


pRstTitles->Fields->GetItem("type")->Value = (_bstr_t) ("database");

// Display the results of the change.


printf("\nBefore resync: \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);

// Resync with database.


pRstTitles->Resync(adAffectAll,adResyncAllValues);

// Display the results of the resynch.


printf("\n\nAfter resync: \n\n");

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();

// 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 (pRstTitles)
if (pRstTitles->State == adStateOpen) {
pRstTitles->CancelBatch(adAffectAll);
pRstTitles->Close();
}
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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\n", pErr->Number, (LPCSTR) pErr->Description);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print COM errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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.

<!-- BeginGetRowsJS -->


<%@ LANGUAGE="JScript" %>
<%// use this meta tag instead of adojavas.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->

<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">

<h1>ADO Recordset.GetRows Example (JScript)</h1>


<!-- Page text goes here -->
<%
var Connect = "Provider='sqloledb';Data Source=" + Request.ServerVariables("SERVER_NAME") + ";" +
"Initial Catalog='Northwind';Integrated Security='SSPI';";
var mySQL = "select * from customers;";
var showblank = " ";
var shownull = "-null-";

var connTemp = Server.CreateObject("ADODB.Connection");

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">');

// Headings On The Table for each Field Name


for (var i=0; i<rsTemp.Fields.Count; i++)
{
fieldObject = rsTemp.fields(i);
Response.Write('<td width="' + Math.floor(100 / rsTemp.Fields.Count) + '%">' + fieldObject.name
+ "</td>");
}

Response.Write("</tr>");

// JScript doesn't support multi-dimensional arrays


// so we'll convert the returned array to a single
// dimensional JScript array and then display the data.
tempArray = rsTemp.GetRows();
recArray = tempArray.toArray();

var col = 1;
var maxCols = rsTemp.Fields.Count;

for (var thisField=0; thisField<recArray.length; thisField++)


{
if (col == 1)
Response.Write('<tr class="tbody">');
if (recArray[thisField] == null)
recArray[thisField] = shownull;
if (recArray[thisField] == "")
recArray[thisField] = showblank;
Response.Write("<td>" + recArray[thisField] + "</td>");
col++
if (col > maxCols)
{
Response.Write("</tr>");
col = 1;
}
}
Response.Write("</table>");
}
}
catch (e)
{
Response.Write(e.message);
}
finally
{
// clean up
if (rsTemp.State == adStateOpen)
rsTemp.Close;
rsTemp.Close;
if (connTemp.State == adStateOpen)
connTemp.Close;
rsTemp = null;
connTemp = null;
}
%>

</body>

</html>
<!-- EndGetRowsJS -->

See Also
GetRows Method (ADO )
Recordset Object (ADO )
LockTypeEnum
10/1/2018 • 2 minutes to read • Edit Online

Specifies the type of lock placed on records during editing.

CONSTANT VALUE DESCRIPTION

adLockBatchOptimistic 4 Indicates optimistic batch updates.


Required for batch update mode.

adLockOptimistic 3 Indicates optimistic locking, record by


record. The provider uses optimistic
locking, locking records only when you
call the Update method.

adLockPessimistic 2 Indicates pessimistic locking, record by


record. The provider does what is
necessary to ensure successful editing
of the records, usually by locking
records at the data source immediately
after editing.

adLockReadOnly 1 Indicates read-only records. You cannot


alter the data.

adLockUnspecified -1 Does not specify a type of lock. For


clones, the clone is created with the
same lock type as the original.

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

Clone Method (ADO) LockType Property (ADO)


Open Method (ADO Recordset) WillExecute Event (ADO)
Open Method (ADO Stream)
10/1/2018 • 2 minutes to read • Edit Online

Opens a Stream object to manipulate streams of binary or text data.

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.

Settings and Return Values


Sets or returns a String value that is the name of a table, schema, or catalog.

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.

IADOCommandConstruction Used to retrieve the underlying OLEDB Command from an


ADOCommand object.

ADORecordConstruction Constructs an ADO Record object from an OLE DB Row


object in a C/C++ application.

ADORecordsetConstruction Constructs an ADO Recordset object from an OLE DB


Rowset object in a C/C++ application.

ADOStreamConstruction Interface Constructs an ADO Stream object from an OLE DB IStream


object in a C/C++ application.

Command Defines a specific command that you intend to execute


against a data source.

The Command object is not safe for scripting.

Connection Represents an open connection to a data source.

The Connection object is safe for scripting.

IDSOShapeExtensions Interface Gets the underlying OLEDB Data Source object for the SHAPE
provider.

Error Contains details about data access errors that pertain to a


single operation involving the provider.

The Error object is not safe for scripting.

Field Represents a column of data with a common data type.

Parameter Represents a parameter or argument associated with a


Command object based on a parameterized query or stored
procedure.

The Parameter object is not safe for scripting.

Property Represents a dynamic characteristic of an ADO object that is


defined by the provider.

Record Represents a row of a Recordset, or a directory or file in a file


system. The Record object is safe for scripting.
Recordset Represents the 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.

The Recordset object is safe for scripting.

Stream Represents a binary stream of data.

The Stream object is safe for scripting.

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

Compares two bookmarks and returns an indication of their relative values.

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

public void appendChunk(byte[] bytes)


public void appendChunk(char[] chars)
public void appendChunk(String chars)

Properties

public int getAttributes()


public void setAttributes(int attr)
public int getDirection()
public void setDirection(int dir)
public String getName()
public void setName(String name)
public int getNumericScale()
public void setNumericScale(int scale)
public int getPrecision()
public void setPrecision(int prec)
public int getSize()
public void setSize(int size)
public int getType()
public void setType(int type)
public com.ms.com.Variant getValue()
public void setValue(Object v)
public AdoProperties getProperties()

Parameter Accessor Methods


The Value property of a Parameter object gets or sets the content of that object. The content is represented as a
VARIANT, a type of object that can be assigned a value and any of several data types.
ADO/WFC implements the Value property with the getValue method, which returns a VARIANT object; and the
setValue method, which takes a VARIANT as an argument. VARIANTs are highly efficient in certain languages,
such as Microsoft Visual Basic.
In addition to the Value property, ADO/WFC provides accessor methods that use Java data types to get and set
the content of Parameter objects. Most of these methods have names of the form getDataType or setDataType.
There is one noteworthy exception: There is no getNull property; instead, there is an isNull property that returns
a Boolean value indicating whether the field is null.
public boolean getBoolean()
public void setBoolean(boolean v)
public byte getByte()
public void setByte(byte v)
public double getDouble()
public void setDouble(double v)
public float getFloat()
public void setFloat(float v)
public int getInt()
public void setInt(int v)
public long getLong()
public void setLong(long v)
public short getShort()
public void setShort(short v)
public String getString()
public void setString(String v)
public boolean isNull()
public void setNull()

See Also
Parameter Object
Name Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Indicates the name of an object.

Settings and Return Values


Sets or returns a String value that indicates the name of an object.

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

Command Object (ADO) Field Object

Parameter Object Property Object (ADO)

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.

CONSTANT VALUE DESCRIPTION

adReadAll -1 Default. Reads all bytes from the


stream, from the current position
onwards to the EOS marker. This is the
only valid StreamReadEnum value
with binary streams (Type is
adTypeBinary).

adReadLine -2 Reads the next line from the stream


(designated by the LineSeparator
property).

ADO/WFC Equivalent
These constants do not have ADO/WFC equivalents.

Applies To

Read Method ReadText Method


Command (ADO for Visual C++ Syntax)
10/1/2018 • 2 minutes to read • Edit Online

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"

//This Class extracts only fname,lname from employee table.


class CEmployeeRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CEmployeeRs)

// fname is the 1st field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, m_sze_fname,
sizeof(m_sze_fname), le_fnameStatus, FALSE)

// lname is the 2nd field in the recordset.


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_sze_lname,
sizeof(m_sze_lname), le_lnameStatus, FALSE)

END_ADO_BINDING()

public:
CHAR m_sze_lname[31];
ULONG le_lnameStatus;
CHAR m_sze_fname[21];
ULONG le_fnameStatus;
};

// This Class extracts only empid,fname,lname,from employee table.


class CEmployeeRs1 : public CADORecordBinding {
BEGIN_ADO_BINDING(CEmployeeRs1)

// emp_id is the 1st field in the table.


ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, m_sze_empid,
sizeof(m_sze_empid), le_empidStatus, FALSE)

// fname is the 2nd field in the table.


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_sze_fname,
sizeof(m_sze_fname), le_fnameStatus, FALSE)

// lname is the 4rt field in the table.


ADO_VARIABLE_LENGTH_ENTRY2(4, adVarChar, m_sze_lname,
sizeof(m_sze_lname), le_lnameStatus, FALSE)

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;

// Define string variables.


_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");

IADORecordBinding *picRs = NULL; // Interface Pointer declared


CEmployeeRs emprs; // C++ Class object.

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

// Store original data.


_bstr_t strOldFirst = pRstEmployees->Fields->GetItem("fname")->Value;
_bstr_t strOldLast = pRstEmployees->Fields->GetItem("lname")->Value;

// Change data in edit buffer.


pRstEmployees->Fields->GetItem("fname")->Value = (_bstr_t)("Linda");
pRstEmployees->Fields->GetItem("lname")->Value = (_bstr_t)("Kobara");

// Show contents of buffer and get user input.


printf("\n\nEdit in progress:\n\n");

printf("Original data = %s %s \n", (LPSTR)strOldFirst, (LPSTR)strOldLast);

printf("Data in buffer = %s %s",


(LPSTR)(_bstr_t) pRstEmployees->Fields->GetItem("fname")->Value,\
(LPSTR) (_bstr_t) pRstEmployees->Fields->GetItem("lname")->Value);

// Ask if the User wants to Update


printf("\n\nUse Update to replace the original data with the"
" buffered data in the Recordset? (y/n): ");
int chKey = _getch();

if ( toupper(chKey) == 'Y' )
pRstEmployees->Update();
else
pRstEmployees->CancelUpdate();

// Open an IADORecordBinding interface pointer for binding Recordset to a class.


TESTHR(pRstEmployees->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Bind the Recordset to a C++ Class here.


TESTHR(picRs->BindToRecordset(&emprs));
pRstEmployees->MoveFirst();

// Show the resulting data.


printf("\nData in recordset = %s %s", emprs.le_fnameStatus ==
adFldOK ? emprs.m_sze_fname : "<NULL>",
emprs.le_lnameStatus == adFldOK ?
emprs.m_sze_lname : "<NULL>");

// Restore original data because this is a demonstration.


if ((strcmp((char *)strOldFirst, emprs.m_sze_fname) &&
strcmp((char *)strOldLast, emprs.m_sze_lname))) {
pRstEmployees->Fields->GetItem("fname")->Value = strOldFirst;
pRstEmployees->Fields->GetItem("lname")->Value = strOldLast;
pRstEmployees->Update();
}
}
catch(_com_error &e) {
// Display errors, if any. Pass connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstEmployees->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;
}
}

// Clean up objects before exit. Release the IADORecordset Interface here


if (picRs)
picRs->Release();

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;

// Define string variables.


_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");

IADORecordBinding *picRs = NULL; // Interface Pointer declared


CEmployeeRs1 emprs; // C++ Class object.

try {
// Open a connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open(strCnn, "", "", NULL);

// Open recordset with data from Employee table.


TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));
pRstEmployees->CursorType = adOpenKeyset;
pRstEmployees->LockType = adLockOptimistic;
pRstEmployees->Open("employee", _variant_t((IDispatch*)pConnection,true),
adOpenKeyset, adLockOptimistic, adCmdTable);
pRstEmployees->AddNew();
_bstr_t strEmpID = "B-S55555M";
pRstEmployees->Fields->GetItem("emp_id")->Value = strEmpID;
pRstEmployees->Fields->GetItem("fname")->Value = (_bstr_t) ("Bill");
pRstEmployees->Fields->GetItem("lname")->Value = (_bstr_t) ("Sornsin");

// Show contents of buffer and get user input.


printf("\n\nAddNew in progress:\n\n");

printf("Data in buffer = %s , %s %s",


(LPSTR) (_bstr_t) pRstEmployees->Fields->GetItem("emp_id")->Value,
(LPSTR) (_bstr_t) pRstEmployees->Fields->GetItem("fname")->Value,
(LPSTR) (_bstr_t) pRstEmployees->Fields->GetItem("lname")->Value);

printf("\n\nUse Update to save buffer to recordset?(y/n):");


int chKey = _getch();

if ( toupper(chKey) == 'Y') {
pRstEmployees->Update();

// Open IADORecordBinding interface pointer for binding Recordset to a class.


TESTHR(pRstEmployees->QueryInterface(__uuidof(IADORecordBinding),(LPVOID*)&picRs));

// Bind the Recordset to a C++ Class here


TESTHR(picRs->BindToRecordset(&emprs));

// Go to the new record and show the resulting data.


printf ("\n\nData in recordset = %s , %s %s",
emprs.le_empidStatus == adFldOK ?
emprs.m_sze_empid : "<NULL>",
emprs.le_fnameStatus == adFldOK ?
emprs.m_sze_fname : "<NULL>",
emprs.le_lnameStatus == adFldOK ?
emprs.m_sze_lname : "<NULL>");
}
else {
pRstEmployees->CancelUpdate();
printf("\n\nNo new record added.\n");
}
// Delete new data because this is a demonstration.
_bstr_t strSQLDelete("DELETE FROM employee WHERE emp_id = '" + strEmpID + "'");
pConnection->Execute(strSQLDelete, NULL, adExecuteNoRecords);
}

catch(_com_error &e) {
// Display errors, if any. Pass connection pointer accessed from the Connection.
PrintProviderError(pConnection);
PrintComError(e);
}

// Clean up objects before exit. Release the IADORecordset Interface here


if (picRs)
picRs->Release();

if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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';");

// Define ADO object pointers. Initialize pointers on define.


// These are in the ADODB:: namespace.
_RecordsetPtr pRst = NULL;

try {
TESTHR(pRst.CreateInstance(__uuidof(Recordset)));

// Enable Index creation.


pRst->CursorLocation = adUseClient;
pRst->Open ("SELECT * FROM authors", strCnn, adOpenStatic, adLockReadOnly, adCmdText);

// Create the index


pRst->Fields->GetItem("zip")->Properties->GetItem("Optimize")->PutValue("True");

// Find Akiko Yokomoto


pRst->Find("zip = '94595'", 1, adSearchForward);
printf("%s %s %s %s %s",
(LPSTR) (_bstr_t) pRst->Fields->GetItem("au_fname")->Value,
(LPSTR) (_bstr_t) pRst->Fields->GetItem("au_lname")->Value,
(LPSTR) (_bstr_t) pRst->Fields->GetItem("address")->Value,
(LPSTR) (_bstr_t) pRst->Fields->GetItem("city")->Value,
(LPSTR) (_bstr_t) pRst->Fields->GetItem("state")->Value);

// Delete the index


pRst->Fields->GetItem("zip")->Properties->GetItem("Optimize")->PutValue("False");
}
}
catch (_com_error &e) {
// Display errors, if any. Pass connection pointer accessed from the Recordset.
_variant_t vtConnect = pRst->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;
}
}

// Clean up objects before exit.


if (pRst)
if (pRst->State == adStateOpen)
pRst->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print COM errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

Akiko Yokomoto 3 Silver Ct. Walnut Creek CA

See Also
Field Object
Optimize Property-Dynamic (ADO )
put_OLEDBCommand Method
10/1/2018 • 2 minutes to read • Edit Online

This method performs no operation and always returns S_OK.

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

Indicates the type of a Command object.

Settings and Return Values


Sets or returns one or more CommandTypeEnum values.

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.

ADCPROP_ASYNCTHREADPRIORITY_ENUM For an RDS Recordset object, specifies the execution priority


of the asynchronous thread that retrieves data.

ADCPROP_AUTORECALC_ENUM Specifies when the MSDataShape provider re-calculates


aggregate and calculated columns in a hierarchical
Recordset.

ADCPROP_UPDATECRITERIA_ENUM Specifies which fields can be used to detect conflicts during an


optimistic update of a row of the data source with a
Recordset object.

ADCPROP_UPDATERESYNC_ENUM Specifies whether the UpdateBatch method is followed by an


implicit Resync method operation and if so, the scope of that
operation.

AffectEnum Specifies which records are affected by an operation.

BookmarkEnum Specifies a bookmark that indicates where the operation


should begin.

CommandTypeEnum Specifies how a command argument should be interpreted.

CompareEnum Specifies the relative position of two records represented by


their bookmarks.

ConnectModeEnum 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.

ConnectOptionEnum Specifies whether the Open method of a Connection object


should return after (synchronously) or before
(asynchronously) the connection is established.

ConnectPromptEnum Specifies whether a dialog box should be displayed to prompt


for missing parameters when opening a connection to an
ODBC data source.

CopyRecordOptionsEnum Specifies the behavior of the CopyRecord method.

CursorLocationEnum Specifies the location of the cursor engine.

CursorOptionEnum Specifies what functionality the Supports method should test


for.
CursorTypeEnum Specifies the type of cursor used in a Recordset object.

DataTypeEnum Specifies the data type of a Field, Parameter, or Property.

EditModeEnum Specifies the editing status of a record.

ErrorValueEnum Specifies the type of ADO run-time error.

EventReasonEnum Specifies the reason that caused an event to occur.

EventStatusEnum Specifies the current status of the execution of an event.

ExecuteOptionEnum Specifies how a provider should execute a command.

FieldEnum Specifies the special fields referenced in the Fields collection


of a Record object.

FieldAttributeEnum Specifies one or more attributes of a Field object.

FieldStatusEnum Specifies the status of a Field object.

FilterGroupEnum Specifies the group of records to be filtered from a


Recordset.

GetRowsOptionEnum Specifies how many records to retrieve from a Recordset.

IsolationLevelEnum Specifies the level of transaction isolation for a Connection


object.

LineSeparatorsEnum Specifies the character used as a line separator in text Stream


objects.

LockTypeEnum Specifies the type of lock placed on records during editing.

MarshalOptionsEnum Specifies which records should be returned to the server.

MoveRecordOptionsEnum Specifies the behavior of the Record object MoveRecord


method.

ObjectStateEnum Specifies whether an object is open or closed, connecting to a


data source, executing a command, or fetching data.

ParameterAttributesEnum Specifies the attributes of a Parameter object.

ParameterDirectionEnum Specifies whether the Parameter represents an input


parameter, an output parameter, or both, or if the parameter
is the return value from a stored procedure.

PersistFormatEnum Specifies the format in which to save a Recordset.

PositionEnum Specifies the current position of the record pointer within a


Recordset.
PropertyAttributesEnum Specifies the attributes of a Property object.

RecordCreateOptionsEnum Specifies for the Record object Open method whether an


existing Record should be opened, or a new Record should
be created.

RecordOpenOptionsEnum Specifies options for opening a Record. These values may be


combined by using an OR operator.

RecordStatusEnum Specifies the status of a record with regard to batch updates


and other bulk operations.

RecordTypeEnum Specifies the type of Record object.

ResyncEnum Specifies whether underlying values are overwritten by a call


to Resync.

SaveOptionsEnum Specifies whether a file should be created or overwritten when


saving from a Stream object. The values can be combined
with an AND operator.

SchemaEnum Specifies the type of schema Recordset that the


OpenSchema method retrieves. Specifies the direction of a
record search within a Recordset.

SearchDirectionEnum Specifies the direction of a record search within a Recordset.


Specifies the type of Seek to execute.

SeekEnum Specifies the type of Seek to execute. Specifies options for


opening a Stream object. The values can be combined with
an AND operator.

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.

StreamTypeEnum Specifies the type of data stored in a Stream object. Specifies


whether a line separator is appended to the string written to
a Stream object.

StreamWriteEnum Specifies whether a line separator is appended to the string


written to a Stream object. Specifies the format when
retrieving a Recordset as a string.

StringFormatEnum Specifies the format when retrieving a Recordset as a string.


Specifies the transaction attributes of a Connection object.

XactAttributeEnum Specifies the transaction attributes of a Connection object.


See Also
ADO API Reference
ADO Collections
ADO Dynamic Properties
Appendix B: ADO Errors
ADO Events
ADO Methods
ADO Object Model
ADO Objects and Interfaces
ADO Properties
ConnectionString, ConnectionTimeout, and State
Properties Example (VC++)
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.

// 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;

// Define Other Variables


HRESULT hr = S_OK;

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 ODBC tags.


// It is assumed that you have create DSN 'DataPubs' with a user name as
// 'MyUserId' and password as 'MyPassword'.
TESTHR(pConnection2.CreateInstance(__uuidof(Connection)));
pConnection2->ConnectionString = "DSN=DataPubs;UID=MyUserId;PWD=MyPassword;";
pConnection2->Open("", "", "", adConnectUnspecified);
pConnection2->Open("", "", "", adConnectUnspecified);
printf("cnn2 state: %s\n", (LPCTSTR)GetState(pConnection2->State));

// Open a connection using a DSN and OLE DB tags.


TESTHR(pConnection3.CreateInstance(__uuidof(Connection)));
pConnection3->ConnectionString = "Data Source=DataPubs;";
pConnection3->Open("", "", "", adConnectUnspecified);
printf("cnn3 state: %s\n", (LPCTSTR)GetState(pConnection3->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);
}

// Cleanup objects before exit.


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 (pConnection4)
if (pConnection4->State == adStateOpen)
pConnection4->Close();
}

_bstr_t GetState(int intState) {


_bstr_t strState;
switch(intState) {
case adStateClosed:
strState = "adStateClosed";
break;
case adStateOpen:
strState = "adStateOpen";
break;
default:
;
}
return strState;
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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, (LPCSTR)pErr->Description);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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.

CONSTANT VALUE DESCRIPTION

adParamInput 1 Default. Indicates that the parameter


represents an input parameter.

adParamInputOutput 3 Indicates that the parameter represents


both an input and output parameter.

adParamOutput 2 Indicates that the parameter represents


an output parameter.

adParamReturnValue 4 Indicates that the parameter represents


a return value.

adParamUnknown 0 Indicates that the parameter direction is


unknown.

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

CreateParameter Method (ADO) Direction Property


AppendChunk Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Appends data to a large text or binary data Field, or to a Parameter object.

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

Field Object Parameter Object

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.

Settings and Return Values


Sets or returns a Long value that indicates, in seconds, how long to wait for a command to execute. Default is 30.

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

Command Object (ADO) Connection 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)
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"

// class extracts title_id and type from titles table


class CTitleRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CTitleRs)

// Column title_id is the 1st field in the Recordset


ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, m_szau_Title_id, sizeof(m_szau_Title_id), lau_Title_idStatus,
FALSE)

// Column type is the 3rd field in the Recordset


ADO_VARIABLE_LENGTH_ENTRY2(3, adVarChar, m_szau_Type, sizeof(m_szau_Type), lau_TypeStatus, TRUE)

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;

// Define string variables.


_bstr_t strSQLChange("UPDATE Titles SET Type = 'sociology' WHERE Type = 'psychology'");
_bstr_t strSQLChange("UPDATE Titles SET Type = 'sociology' WHERE Type = 'psychology'");
_bstr_t strSQLRestore("UPDATE Titles SET Type = 'psychology' WHERE Type = 'sociology'");

// Define Other Variables


HRESULT hr = S_OK;
IADORecordBinding *picRs = NULL; // Interface Pointer declared
CTitleRs titlers; // C++ Class object
char * token1;

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

// Open Recordset for batch update.


TESTHR(pRstTitles.CreateInstance(__uuidof(Recordset)));
pRstTitles->PutActiveConnection(_variant_t((IDispatch *)pConnection, true));
pRstTitles->CursorType = adOpenKeyset;
pRstTitles->LockType = adLockBatchOptimistic;

// Cast connection pointer to IDispatch type; convert to correct variant type.


pRstTitles->Open("Titles", _variant_t((IDispatch *)pConnection,true),
adOpenKeyset, adLockBatchOptimistic, adCmdTable);

// Open IADORecordBinding interface pointer for Binding Recordset to a class.


TESTHR(pRstTitles->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Bind the Recordset to a C++ Class here


TESTHR(picRs->BindToRecordset(&titlers));

// Set field object variable for Type field.


pFldType = pRstTitles->Fields->GetItem("type");

// Change the type of psychology titles.


while ( !(pRstTitles->EndOfFile) ) {
if (!strcmp(strtok_s((char *)titlers.m_szau_Type, " ", &token1), "psychology"))
pFldType->Value = "self_help";
pRstTitles->MoveNext();
}

// Simulate a change by another user by updating data using a command string.


pConnection->Execute(strSQLChange, NULL, 0);

// Check for changes.


pRstTitles->MoveFirst();
while (!(pRstTitles->EndOfFile)) {
if (strcmp(pFldType->OriginalValue.pcVal, pFldType->UnderlyingValue.pcVal)) {
printf("Data has changed!");

printf("\nTitle ID: %s", titlers.lau_Title_idStatus ==


adFldOK ? titlers.m_szau_Title_id : "<NULL>");

printf("\nCurrent Value: %s", (LPCSTR) (_bstr_t) pFldType->Value);

printf("\nOriginal Value: %s", (LPCSTR) (_bstr_t) pFldType->OriginalValue);

printf("\nUnderlying Value: %s\n\n", (LPCSTR) (_bstr_t) pFldType->UnderlyingValue);


}
pRstTitles->MoveNext();
}
}
catch (_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Connection.
PrintProviderError(pConnection);
PrintComError(e);
}
}

// Clean up objects before exit. Release the IADORecordset Interface here


if (picRs)
picRs->Release();

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();
}
};

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print COM errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

Data has changed!


Title ID: PS1372
Current Value: self_help
Original Value: psychology
Underlying Value: sociology
Data has changed!
Title ID: PS2091
Current Value: self_help
Original Value: psychology
Underlying Value: sociology
Data has changed!
Title ID: PS2106
Current Value: self_help
Original Value: psychology
Underlying Value: sociology
Data has changed!
Title ID: PS3333
Current Value: self_help
Original Value: psychology
Underlying Value: sociology
Data has changed!
Title ID: PS7777
Current Value: self_help
Original Value: psychology
Underlying Value: sociology

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.

Settings and Return Values


Sets and returns a ConnectPromptEnum value.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

'recordset and connection variables


Dim rstEmployees As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQL As String
'record variables
Dim strMessage As String

'Open connection
Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open Employee recordset with


' Client-side cursor to enable AbsolutePosition property
Set rstEmployees = New ADODB.Recordset
strSQL = "employee"
rstEmployees.Open strSQL, strCnxn, adUseClient, adLockReadOnly, adCmdTable

' Enumerate Recordset


Do While Not rstEmployees.EOF
' Display current record information
strMessage = "Employee: " & rstEmployees!lname & vbCr & _
"(record " & rstEmployees.AbsolutePosition & _
" of " & rstEmployees.RecordCount & ")"
If MsgBox(strMessage, vbOKCancel) = vbCancel Then Exit Do
rstEmployees.MoveNext
Loop

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndAbsolutePositionVB

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.

Public Sub Main()


On Error GoTo ErrorHandler

' connection and recordset variables


Dim rsDestFolder As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String

' file as record variables


Dim rcFile As ADODB.Record
Dim rcDestFile As ADODB.Record
Dim rcDestFolder As ADODB.Record
Dim objStream As Stream

' file variables


Dim strFile As String
Dim strDestFile As String
Dim strDestFolder As String

' instantiate variables


Set rsDestFolder = New ADODB.Recordset
Set rcDestFolder = New ADODB.Record
Set rcFile = New ADODB.Record
Set rcDestFile = New ADODB.Record
Set objStream = New ADODB.Stream

' open a record on a text file


Set Cnxn = New ADODB.Connection
strCnxn = "url=https://MyServer/"
Cnxn.Open strCnxn
strFile = "test/test2.txt"
rcFile.Open strFile, Cnxn, adModeReadWrite, adOpenIfExists Or adCreateNonCollection
Debug.Print Cnxn

' edit the contents of the text file


objStream.Open rcFile, , adOpenStreamFromRecord

Debug.Print "Source: " & strCnxn & rcFile.Source


Debug.Print "Original text: " & objStream.ReadText
objStream.Position = 0
objStream.WriteText "Newer Text. "
objStream.Position = 0

Debug.Print "New text: " & objStream.ReadText

' reset the stream object


objStream.Flush
objStream.Close
rcFile.Close

' reopen record to see new contents of text file


rcFile.Open strFile, Cnxn, adModeReadWrite, adOpenIfExists Or adCreateNonCollection
objStream.Open rcFile, adModeReadWrite, adOpenStreamFromRecord

Debug.Print "Source: " & strCnxn & rcFile.Source


Debug.Print "Edited text: " & objStream.ReadText

' copy the file to another folder


strDestFile = "test2/test1.txt"
rcFile.CopyRecord "", "https://MyServer/" & strDestFile, "", "", adCopyOverWrite

' delete the original file


rcFile.DeleteRecord

' 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

' position current record at on the correct file


Do While Not (rsDestFolder.EOF Or rsDestFolder(0) = "test1.txt")
rsDestFolder.MoveNext
Loop

' open a record on the correct row of the recordset


rcDestFile.Open rsDestFolder, Cnxn

' do the move


rcDestFile.MoveRecord "", "https://MyServer/" & strFile, "", "", adMoveOverWrite

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndDeleteRecordVB
See Also
DeleteRecord Method (ADO )
Flush Method (ADO )
GetChildren Method (ADO )
MoveRecord Method (ADO )
ParentURL Property (ADO )
Source Property (ADO Record)
AppendChunk and GetChunk Methods Example (VB)
10/1/2018 • 2 minutes to read • Edit Online

This example uses the AppendChunk and GetChunk methods to fill an image field with data from another record.

'BeginAppendChunkVB

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

'recordset and connection variables


Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim rstPubInfo As ADODB.Recordset
Dim strSQLPubInfo As String
'record variables
Dim strPubID As String
Dim strPRInfo As String
Dim lngOffset As Long
Dim lngLogoSize As Long
Dim varLogo As Variant
Dim varChunk As Variant
Dim strMsg As String

Const conChunkSize = 100

' Open a connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' 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

' Prompt for a logo to copy


strMsg = "Available logos are : " & vbCr & vbCr
Do While Not rstPubInfo.EOF
strMsg = strMsg & rstPubInfo!pub_id & vbCr & _
Left(rstPubInfo!pr_info, InStr(rstPubInfo!pr_info, ",") - 1) & _
vbCr & vbCr
rstPubInfo.MoveNext
Loop

strMsg = strMsg & "Enter the ID of a logo to copy:"


strPubID = InputBox(strMsg)

' Copy the logo to a variable in chunks


rstPubInfo.Filter = "pub_id = '" & strPubID & "'"
lngLogoSize = rstPubInfo!logo.ActualSize
Do While lngOffset < lngLogoSize
varChunk = rstPubInfo!logo.GetChunk(conChunkSize)
varLogo = varLogo & varChunk
lngOffset = lngOffset + conChunkSize
Loop

' Get data from the user


' Get data from the user
strPubID = Trim(InputBox("Enter a new pub ID" & _
" [must be > 9899 & < 9999]:"))

strPRInfo = Trim(InputBox("Enter descriptive text:"))

' Add the new publisher to the publishers table to avoid


' getting an error due to foreign key constraint
Cnxn.Execute "INSERT publishers(pub_id, pub_name) VALUES('" & _
strPubID & "','Your Test Publisher')"

' Add a new record, copying the logo in chunks


rstPubInfo.AddNew
rstPubInfo!pub_id = strPubID
rstPubInfo!pr_info = strPRInfo

lngOffset = 0 ' Reset offset


Do While lngOffset < lngLogoSize
varChunk = LeftB(RightB(varLogo, lngLogoSize - lngOffset), _
conChunkSize)
rstPubInfo!logo.AppendChunk varChunk
lngOffset = lngOffset + conChunkSize
Loop
rstPubInfo.Update

' Show the newly added data


MsgBox "New record: " & rstPubInfo!pub_id & vbCr & _
"Description: " & rstPubInfo!pr_info & vbCr & _
"Logo size: " & rstPubInfo!logo.ActualSize

' Delete new records because this is a demo


rstPubInfo.Requery
Cnxn.Execute "DELETE FROM pub_info " & _
"WHERE pub_id = '" & strPubID & "'"

Cnxn.Execute "DELETE FROM publishers " & _


"WHERE pub_id = '" & strPubID & "'"

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndAppendChunkVB

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.

<!-- BeginAbsolutePositionJS -->


<%@LANGUAGE="JScript" %>
<%// use this meta tag instead of adojavas.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->

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

// Write beginning of table to the document.


Response.Write('<table border="0" align="center">');
Response.Write('<table border="0" align="center">');
Response.Write('<tr class="thead2">');
Response.Write("<th>AbsolutePosition</th><th>Name</th><th>Hire Date</th></tr>");

while (!rsEmployee.EOF)
{
strMessage = "";

// Start a new table row.


strMessage = '<tr class="tbody">';

// First column in row contains AbsolutePosition value.


strMessage += "<td>" + rsEmployee.AbsolutePosition + " of " + rsEmployee.RecordCount + "</td>"

// First and last name are in first column.


strMessage += "<td>" + rsEmployee.Fields("FirstName") + " ";
strMessage += rsEmployee.Fields("LastName") + " " + "</td>";

// Hire date in second column.


strMessage += "<td>" + rsEmployee.Fields("HireDate") + "</td>";

// End the row.


strMessage += "</tr>";

// Write line to document.


Response.Write(strMessage);

// Get next record.


rsEmployee.MoveNext;
}

// Finish writing document.


Response.Write("</table>");
}
catch (e)
{
Response.Write(e.message);
}
finally
{
// 'clean up
if (rsEmployee.State == adStateOpen)
rsEmployee.Close;
rsEmployee = null;
}
%>

</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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

'recordset and connection variables


Dim rstStores As ADODB.Recordset
Dim SQLStores As String
Dim strCnxn As String
'record variables
Dim strMessage As String

' Open a recordset for the Stores table


strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Northwind';Integrated Security='SSPI';"
Set rstStores = New ADODB.Recordset

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

' Loop through the recordset displaying the contents


' of the store_name field, the field's defined size,
' and its actual size.
rstStores.MoveFirst

Do Until rstStores.EOF
strMessage = "Company name: " & rstStores!CompanyName & _
vbCrLf & "Defined size: " & _
rstStores!CompanyName.DefinedSize & _
vbCrLf & "Actual size: " & _
rstStores!CompanyName.ActualSize & vbCrLf

MsgBox strMessage, vbOKCancel, "ADO ActualSize Property (Visual Basic)"


rstStores.MoveNext
Loop

' 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

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndActualSizeVB

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

CONSTANT VALUE DESCRIPTION

adAsyncConnect 16 Opens the connection asynchronously.


The ConnectComplete event may be
used to determine when the connection
is available.

adConnectUnspecified -1 Default. Opens the connection


synchronously.

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

Reads specified number of characters from a text Stream object.

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

Specifies the special fields referenced in a Record object's Fields collection.

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.

CONSTANT VALUE DESCRIPTION

adDefaultStream -1 References the field containing the


default Stream object associated with a
Record.

adRecordURL -2 References the field containing the


absolute URL string for the current
Record.
ActiveCommand Property Example (JScript)
10/1/2018 • 2 minutes to read • Edit Online

This example demonstrates the ActiveCommand property. Cut and paste the following code to Notepad or
another text editor, and save it as ActiveCommandJS.asp.

<!-- BeginActiveCommandJS -->


<%@LANGUAGE="JScript" %>
<%// use this meta tag instead of adojavas.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->

<%
// 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">

<h1>ActiveCommand Property Example (JScript)</h1>

<%
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);

// Open a recordset using a command object


cmdContact.CommandText = "SELECT ContactName FROM Customers WHERE City = ?";
cmdContact.ActiveConnection = Cnxn;
// create parameter and insert variable value
cmdContact.Parameters.Append(cmdContact.CreateParameter("ContactName", adChar, adParamInput, 30,
strName));

rsContact = cmdContact.Execute();

while(!rsContact.EOF){
while(!rsContact.EOF){
// start new line
strMessage = "<P>";

// get data
strMessage += rsContact("ContactName")

// end the line


strMessage += "</P>";

// show data
Response.Write(strMessage);

// get next record


rsContact.MoveNext;
}
}
catch (e)
{
Response.Write(e.message);
}
finally
{
// 'clean up
if (rsContact.State == adStateOpen)
rsContact.Close;
if (Cnxn.State == adStateOpen)
Cnxn.Close;
rsContact = null;
Cnxn = null;
}
}
%>

<hr>

<form method="POST" action="ActiveCommandJS.asp">


<p align="left">Enter city of customer to find (e.g., Paris): <input type="text" name="ContactName"
size="40" value=""></p>
<p align="left"><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2">
</p>
</form>
</body>

</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.

CONSTANT VALUE DESCRIPTION

adWriteChar 0 Default. Writes the specified text string


(specified by the Data parameter) to
the Stream object.

adWriteLine 1 Writes a text string and a line separator


character to a Stream object. If the
LineSeparator property is not defined,
then this returns a run-time error.

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"

// class extracts only author id,fname,lastname


class CEmployeeRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CEmployeeRs)

// Column au_id is the 1st field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, m_szau_id, sizeof(m_szau_id), lau_idStatus, TRUE)

ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_szau_lname, sizeof(m_szau_lname), lau_lnameStatus, TRUE)

ADO_VARIABLE_LENGTH_ENTRY2(3, adVarChar, m_szau_fname, sizeof(m_szau_fname), lau_fnameStatus, TRUE)

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;

//Define Other variables


IADORecordBinding *picRs = NULL; // Interface Pointer declared.(VC++ Extensions)
CEmployeeRs emprs; // C++ class object

_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated


Security='SSPI';");

_bstr_t strMessage, strAuthorID;

int intRoyalty;
VARIANT vtRoyalty;

try {
// Open a Connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
hr = pConnection->Open(strCnn, "", "", adConnectUnspecified);
pConnection->CursorLocation = adUseClient;

// Open Command Object with one Parameter


TESTHR(pcmdByRoyalty.CreateInstance(__uuidof(Command)));
pcmdByRoyalty->CommandText = "byroyalty";
pcmdByRoyalty->CommandType = adCmdStoredProc;

// Get parameter value and append parameter


printf("Enter Royalty: ");
scanf_s("%d", &intRoyalty);

// 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;

// Create Recordset by executing the command


pcmdByRoyalty->ActiveConnection = pConnection;
pRstByRoyalty = pcmdByRoyalty->Execute(NULL, NULL, adCmdStoredProc);

// Open the authors table to get author names for display


TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));

// 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));

// Bind the Recordset to a C++ Class here


TESTHR(picRs->BindToRecordset(&emprs));

// 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+"'";

printf("\n" "%s, %s %s",emprs.lau_idStatus == adFldOK ? emprs.m_szau_id : "<NULL>",\


emprs.lau_fnameStatus == adFldOK ? emprs.m_szau_fname : "<NULL>",\
emprs.lau_lnameStatus == adFldOK ? emprs.m_szau_lname : "<NULL>");

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);
}

// Clean up objects before exit. Release the IADORecordset Interface here


if (picRs)
picRs->Release();

if (pRstByRoyalty)
if (pRstByRoyalty->State == adStateOpen)
pRstByRoyalty->Close();
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;
long nCount = 0;
long i = 0;

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

public void addNew(Object[] fieldList, Object[] valueList)


public void addNew(Object[] valueList)
public void addNew()
public void cancel()
public void cancelBatch(int affectRecords)
public void cancelBatch()
public void cancelUpdate()
public Object clone()
public Object clone(int lockType)
public void close()
public int compareBookmarks(Object bookmark1, Object bookmark2)
public void delete(int affectRecords)
public void delete()
public void find(String criteria)
public void find(String criteria, int SkipRecords)
public void find(String criteria, int SkipRecords, int searchDirection)
public void find(String criteria, int SkipRecords, int searchDirection, Object bmkStart)
public Object[][] getRows(int Rows, Object bmkStart, Object[] fieldList)
public void move(int numRecords)
public void move(int numRecords, Object bmkStart)
public void moveFirst()
public void moveLast()
public void moveNext()
public void movePrevious()
public Recordset nextRecordset()
public Recordset nextRecordset(int[] recordsAffected)
public void open()
public void open(Object source)
public void open(Object source, Object activeConnection)
public void open(Object source, Object activeConnection, int cursorType)
public void open(Object source, Object activeConnection, int cursorType,
int lockType)
public void open(Object source, Object activeConnection, int cursorType,
int lockType, int options)
public void requery()
public void requery(int options)
public void resync()
public void resync(int affectRecords, int resyncValues)
public void save(String fileName)
public void save(String fileName, int persistFormat)
public boolean supports(int cursorOptions)
public void update()
public void update(Object[] valueList)
public void update(Object[] fieldList, Object[] valueList)
public void updateBatch()
public void updateBatch(int affectRecords)
Properties

public int getAbsolutePage()


public void setAbsolutePage(int page)
public int getAbsolutePosition()
public void setAbsolutePosition(int pos)
public Command getActiveCommand()
public Connection getActiveConnection()
public void setActiveConnection(String conn)
public void setActiveConnection(com.ms.wfc.data.Connection c)
public boolean getBOF()
public boolean getEOF()
public Object getBookmark()
public void setBookmark(Object bmk)
public int getCacheSize()
public void setCacheSize(int size)
public int getCursorLocation()
public void setCursorLocation(int cursorLoc)
public int getCursorType()
public void setCursorType(int cursorType)
public String getDataMember()
public void setDataMember(String pbstrDataMember)
public Iunknown getDataSource()
public void setDataSource(IUnknown dataSource)
public int getEditMode()
public Object getFilter()
public void setFilter(Object filter)
public int getLockType()
public void setLockType(int lockType)
public int getMarshalOptions()
public void setMarshalOptions(int options)
public int getMaxRecords()
public void setMaxRecords(int maxRecords)
public int getPageCount()
public int getPageSize()
public void setPageSize(int pageSize)
public int getRecordCount()
public String getSort()
public void setSort(String criteria)
public String getSource()
public void setSource(String query)
public void setSource(com.ms.wfc.data.Command command)
public int getState()
public int getStatus()
public boolean getStayInSync()
public void setStayInSync(boolean pbStayInSync)
public com.ms.wfc.data.Field getField(int n)
public com.ms.wfc.data.Field getField(String n)
public com.ms.wfc.data.Fields getFields()
public AdoProperties getProperties()

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"

// class extracts titles and type from Titles table


class CTitleRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CTitleRs)

// Column title is the 2nd field in the table


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_szt_Title, sizeof(m_szt_Title), lt_TitleStatus, FALSE)

// Column type is the 3rd field in the table


ADO_VARIABLE_LENGTH_ENTRY2(3, adVarChar, m_szt_Type, sizeof(m_szt_Type), lt_TypeStatus, TRUE)
END_ADO_BINDING()

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;

// Define ADO object pointers. // Initialize pointers on define.


// These are in the ADODB:: namespace.
_RecordsetPtr pRstTitles = NULL;
char * token1;

// Define string variables.


_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");

IADORecordBinding *picRs = NULL; // Interface Pointer Declared


CTitleRs titlers; // C++ Class Object
CTitleRs titlers; // C++ Class Object

try {
// Open titles table.
TESTHR(pRstTitles.CreateInstance(__uuidof(Recordset)));
pRstTitles->CursorType = adOpenKeyset;
pRstTitles->LockType = adLockBatchOptimistic;
pRstTitles->Open ("titles", strCnn, adOpenKeyset, adLockBatchOptimistic, adCmdTable);

// Open IADORecordBinding interface pointer for binding recordset to a class


TESTHR(pRstTitles->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Binding the Recordset to a C++ Class


TESTHR(picRs->BindToRecordset(&titlers));
pRstTitles->MoveFirst();

// Loop through recordset and ask user if she wants,


// to change the type for a specified title.
while (!(pRstTitles->EndOfFile)) {
// Compare type with psychology
if (!strcmp( (char *)strtok_s(titlers.m_szt_Type, " ", &token1), "psychology" )) {
printf("\n\nTitle: %s \nChange type to self_help?(y/n):", titlers.m_szt_Title);
char chKey;
chKey = _getch();
if (toupper(chKey) == 'Y') {
// Change type to self_help.
pRstTitles->Fields->GetItem("type")->Value = (_bstr_t)("self_help");
}
}
pRstTitles->MoveNext();
}

// commit all the changes made above?


printf("\n\nSave all changes?");
char chKey;
chKey = _getch();
if (toupper(chKey) == 'Y')
pRstTitles->UpdateBatch(adAffectAll);
else
pRstTitles->CancelBatch(adAffectAll);

// Print current data in recordset.


pRstTitles->Requery(adOptionUnspecified);

// Open IADORecordBinding interface pointer for Binding Recordset to a class


TESTHR(pRstTitles->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// ReBinding the Recordset to a C++ Class.


TESTHR(picRs->BindToRecordset(&titlers));

// Move to the first record of the title table


pRstTitles->MoveFirst();

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();

// Restore original data because this is demonstration.


while (!(pRstTitles->EndOfFile)) {
// Compare type with psychology
if (!strcmp( (char *)strtok_s(titlers.m_szt_Type, " ", &token1), "self_help" )) {
if (!strcmp( (char *)strtok_s(titlers.m_szt_Type, " ", &token1), "self_help" )) {
// Change type to psychology.
pRstTitles->Fields->GetItem("type")->Value = (_bstr_t)("psychology");
}
pRstTitles->MoveNext();
}
}
catch (_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstTitles->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 (pRstTitles)
if (pRstTitles->State == adStateOpen) {
pRstTitles->UpdateBatch(adAffectAll);
pRstTitles->Close();
}
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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.

CONSTANT VALUE DESCRIPTION

adResyncAll 15 Invokes Resync with the combined


value of all the other
ADCPROP_UPDATERESYNC_ENUM
members.

adResyncAutoIncrement 1 Default. Attempts to retrieve the new


identity value for columns that are
automatically incremented or generated
by the data source, such as Microsoft
Jet AutoNumber fields or Microsoft SQL
Server Identity columns.

adResyncConflicts 2 Invokes Resync for all rows in which


the update or delete operation failed
because of a concurrency conflict.

adResyncInserts 8 Invokes Resync for all successfully


inserted rows. However, AutoIncrement
column values are not resynchronized.
Instead, the contents of newly inserted
rows are resynchronized based on the
existing primary key value. If the
primary key is an AutoIncrement value,
Resync won't retrieve the contents of
the intended row. For automatically
incrementing AutoIncrement primary
key values, call UpdateBatch with the
combined value
adResyncAutoIncrement +
adResyncInserts.

adResyncNone 0 Does not invoke Resync.

adResyncUpdates 4 Invokes Resync for all successfully


updated rows.

Applies To
Update Resync Property-Dynamic (ADO )
CompareEnum
10/1/2018 • 2 minutes to read • Edit Online

Specifies the relative position of two records represented by their bookmarks.

CONSTANT VALUE DESCRIPTION

adCompareEqual 1 Indicates that the bookmarks are equal.

adCompareGreaterThan 2 Indicates that the first bookmark is


after the second.

adCompareLessThan 0 Indicates that the first bookmark is


before the second.

adCompareNotComparable 4 Indicates that the bookmarks cannot be


compared.

adCompareNotEqual 3 Indicates that the bookmarks are not


equal and not ordered.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

' connection and recordset variables


Dim Cnxn As New ADODB.Connection
Dim rstTitles As New ADODB.Recordset
Dim strCnxn As String
Dim strSQLTitles As String

' record variables


Dim mark As Variant
Dim count As Integer

' open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' open recordset with default parameters which are


' sufficient to search forward through a Recordset
Set rstTitles = New ADODB.Recordset
strSQLTitles = "SELECT title_id FROM titles"
rstTitles.Open strSQLTitles, Cnxn, adOpenStatic, adLockReadOnly, adCmdText

count = 0
rstTitles.Find "title_id LIKE 'BU%'"

Do While Not rstTitles.EOF


'continue if last find succeeded
Debug.Print "Title ID: "; rstTitles!title_id
'count the last title found
count = count + 1
' note current position
mark = rstTitles.Bookmark
rstTitles.Find "title_id LIKE 'BU%'", 1, adSearchForward, mark
' above code skips current record to avoid finding the same row repeatedly;
' last arg (bookmark) is redundant because Find searches from current position
Loop

Debug.Print "The number of business titles is " & count

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndFindVB

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( );

_bstr_t CopyRecord( _bstr_t Source, _bstr_t Destination,


_bstr_t UserName, _bstr_t Password, enum CopyRecordOptionsEnum
Options, VARIANT_BOOL Async );

HRESULT DeleteRecord( _bstr_t Source, VARIANT_BOOL Async );

_RecordsetPtr GetChildren( );

_bstr_t MoveRecord( _bstr_t Source, _bstr_t Destination,


_bstr_t UserName, _bstr_t Password, enum MoveRecordOptionsEnum
Options, VARIANT_BOOL Async );

HRESULT Open( const _variant_t & Source, const _variant_t


& ActiveConnection, enum ConnectModeEnum Mode, enum
RecordCreateOptionsEnum CreateOptions, enum RecordOpenOptionsEnum
Options, _bstr_t UserName, _bstr_t Password );

Properties
_variant_t GetActiveConnection( );
void PutActiveConnection( _bstr_t pvar );
void PutRefActiveConnection( struct _Connection * pvar );

FieldsPtr GetFields( );
__declspec(property(get=GetFields)) FieldsPtr Fields;

enum ConnectModeEnum GetMode( );


void PutMode( enum ConnectModeEnum pMode );
__declspec(property(get=GetMode,put=PutMode)) enum ConnectModeEnum Mode;

_bstr_t GetParentURL( );
__declspec(property(get=GetParentURL)) _bstr_t ParentURL;

enum RecordTypeEnum GetRecordType( );


__declspec(property(get=GetRecordType)) enum RecordTypeEnum
RecordType;

_variant_t GetSource( );
void PutSource( _bstr_t pvar );
void PutRefSource( IDispatch * pvar );

enum ObjectStateEnum GetState( );


__declspec(property(get=GetState)) enum ObjectStateEnum State;

See Also
Record Object (ADO )
CopyRecord Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Copies an entity represented by a record to another location.

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

Indicates the provider-specific error code for a given Error object.

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"

// Class extracts only Pub Name and Country Name.


class CPublishers : public CADORecordBinding {
BEGIN_ADO_BINDING(CPublishers)

// Column Pub Name is the 2nd field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_szP_pubname, sizeof(m_szP_pubname),
lP_pubnameStatus, TRUE)

// Column Country Name is the 5th field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(5, adVarChar, m_szP_country, sizeof(m_szP_country),
lP_countryStatus, TRUE)

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

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 {
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;

// Define Other Variables


HRESULT hr = S_OK;
_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");
int intPublisherCount = 0;
long recCount = 0;
_bstr_t strCountry;
_bstr_t strMessage;
char *tempStr;
CHAR sz_CountryName[50];
bool boolFlag = TRUE;
char * token1;

try {
// Open recordset with data from Publishers table.
rstPublishers.CreateInstance(__uuidof(Recordset));
rstPublishersCountry.CreateInstance(__uuidof(Recordset));

rstPublishers->CursorType = adOpenStatic;

TESTHR(rstPublishers->Open("publishers", strCnn, adOpenStatic , adLockReadOnly, adCmdTable));

// Populate the Recordset.


intPublisherCount = rstPublishers->RecordCount;

// Get user input.


printf("Enter a country to filter on:");
mygets(sz_CountryName, 50);

// Trim the string


tempStr = strtok_s(sz_CountryName, " \t", &token1);
strCountry = tempStr;
if (tempStr == NULL)
boolFlag = FALSE;

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();

// 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;
}
}

// Clean up objects before exit.


if (rstPublishers)
if (rstPublishers->State == adStateOpen)
rstPublishers->Close();
if (rstPublishersCountry)
if (rstPublishersCountry->State == adStateOpen)
rstPublishersCountry->Close();
}

_RecordsetPtr FilterField(_RecordsetPtr rstTemp,_bstr_t strField, _bstr_t strFilter) {


// Set a filter on the specified Recordset object and then open a new Recordset object.
rstTemp->Filter = strField + " = '" + strFilter + "'";
return rstTemp;
}

void FilterX2() {
_RecordsetPtr rstPublishers;
CPublishers publishers;

// Define Other Variables


HRESULT hr = S_OK;
IADORecordBinding *picRs = NULL; // Interface Pointer declared

_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated


Security='SSPI';");
try {
// Open recordset with data from Publishers table.
rstPublishers.CreateInstance(__uuidof(Recordset));
rstPublishers->CursorType = adOpenStatic;

TESTHR(rstPublishers->Open("SELECT * FROM publishers WHERE "


"Country='USA'", strCnn, adOpenStatic, adLockReadOnly, adCmdText));

// Open an IADORecordBinding interface pointer


// which we'll use for Binding Recordset to a class
TESTHR(rstPublishers->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Bind the Recordset to a C++ Class here


TESTHR(picRs->BindToRecordset(&publishers));

// Print current data in recordset.


rstPublishers->MoveFirst();

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();

// 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;
}
}

// Clean up objects before exit. Release the IADORecordset Interface here


if (picRs)
picRs->Release();

if (rstPublishers)
if (rstPublishers->State == adStateOpen)
rstPublishers->Close();
}

void PrintProviderError(_ConnectionPtr pCnn1) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

Sample Input
USA

Sample Output
Orders in original recordset:
8
Orders in filtered recordset (Country = 'USA'):
6

New Moon Books, USA


Binnet & Hardley, USA
Algodata Infosystems, USA
Five Lakes Publishing, USA
Ramona Publishers, USA
Scootney Books, USA

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

HRESULT FieldChangeComplete( long cFields, const


_variant_t & Fields, struct Error * pError, enum EventStatusEnum
* adStatus, struct _Recordset * pRecordset );

HRESULT WillChangeRecord( enum EventReasonEnum


adReason, long cRecords, enum EventStatusEnum * adStatus, struct
_Recordset * pRecordset );

HRESULT RecordChangeComplete( enum EventReasonEnum


adReason, long cRecords, struct Error * pError, enum
EventStatusEnum * adStatus, struct _Recordset * pRecordset );

HRESULT WillChangeRecordset( enum EventReasonEnum


adReason, enum EventStatusEnum * adStatus, struct _Recordset *
pRecordset );

HRESULT RecordsetChangeComplete( enum


EventReasonEnum adReason, struct Error * pError, enum
EventStatusEnum * adStatus, struct _Recordset * pRecordset );

HRESULT WillMove( enum EventReasonEnum adReason, enum


EventStatusEnum * adStatus, struct _Recordset * pRecordset );

HRESULT MoveComplete( enum EventReasonEnum adReason, struct


Error * pError, enum EventStatusEnum * adStatus, struct
_Recordset * pRecordset );

HRESULT EndOfRecordset( VARIANT_BOOL * fMoreData, enum


EventStatusEnum * adStatus, struct _Recordset * pRecordset );

HRESULT FetchProgress( long Progress, long MaxProgress,


enum EventStatusEnum * adStatus, struct _Recordset * pRecordset );

HRESULT FetchComplete( struct Error * pError, enum


EventStatusEnum * adStatus, struct _Recordset * pRecordset );
StayInSync Property Example (VB)
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.
'BeginStayInSyncVB
Public Sub Main()
On Error GoTo ErrorHandler

Dim Cnxn As ADODB.Connection


Dim rst As ADODB.Recordset
Dim rstTitleAuthor As New ADODB.Recordset
Dim strCnxn As String

' Open the connection with Data Shape attributes


Set Cnxn = New ADODB.Connection
strCnxn = "Provider=MSDataShape;Data Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Create a recordset


Set rst = New ADODB.Recordset
rst.StayInSync = True
rst.Open "SHAPE {select * from Authors} " & _
"APPEND ( { select * from titleauthor} AS chapTitleAuthor " & _
"RELATE au_id TO au_id) ", Cnxn, , , adCmdText

Set rstTitleAuthor = rst("chapTitleAuthor").Value


Do Until rst.EOF
Debug.Print rst!au_fname & " " & rst!au_lname & " " & _
rst!State & " " & rst!au_id

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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndStayInSyncVB

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

'recordset and connection variables


Dim Cnxn As ADODB.Connection
Dim rstPublishers As ADODB.Recordset
Dim strCnxn As String
Dim strSQLPubs As String
'record variables
Dim strMessage As String
Dim intCommand As Integer
Dim varBookmark As Variant

' open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open recordset and use client cursor


' to enable AbsolutePosition property
Set rstPublishers = New ADODB.Recordset
strSQLPubs = "SELECT pub_id, pub_name FROM publishers ORDER BY pub_name"
rstPublishers.Open strSQLPubs, strCnxn, adUseClient, adOpenStatic, adCmdText

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

' Check user input


Select Case intCommand
Case 1
' Move forward trapping for EOF
rstPublishers.MoveNext
If rstPublishers.EOF Then
MsgBox "Moving past the last record." & _
vbCr & "Try again."
rstPublishers.MoveLast
End If
Case 2
' Move backward trapping for BOF
' Move backward trapping for BOF
rstPublishers.MovePrevious
If rstPublishers.BOF Then
MsgBox "Moving past the first record." & _
vbCr & "Try again."
rstPublishers.MoveFirst
End If
Case 3
' Store the bookmark of the current record
varBookmark = rstPublishers.Bookmark
Case 4
' Go to the record indicated by the stored bookmark
If IsEmpty(varBookmark) Then
MsgBox "No Bookmark set!"
Else
rstPublishers.Bookmark = varBookmark
End If
Case Else
Exit Do
End Select
Loop

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndBOFVB

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.

Attribute VB_Name = "BOF"

See Also
BOF, EOF Properties (ADO )
Bookmark Property (ADO )
Recordset Object (ADO )
CursorType Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Indicates the type of cursor used in a Recordset object.

Settings and Return Values


Sets or returns a CursorTypeEnum value. The default value is adOpenForwardOnly.

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.

THE SUPPORTS METHOD MUST RETURN TRUE FOR ALL OF THESE


FOR A RECORDSET OF THIS CURSORTYPE CONSTANTS

adOpenForwardOnly none

adOpenKeyset adBookmark, adHoldRecords, adMovePrevious,


adResync

adOpenDynamic adMovePrevious

adOpenStatic adBookmark, adHoldRecords, adMovePrevious,


adResync

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

Indicates how many pages of data the Recordset object contains.

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.

Errors Contains all the Error objects created in response to a single


provider-related failure.

Fields Contains all the Field objects of a Recordset object.

Parameters Contains all the Parameter objects of a Command object.

Properties Contains all the Property objects for a specific instance of an


object.

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"

// class extracts only author id,fname,lastname


class CEmployeeRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CEmployeeRs)

// Column au_id is the 1st field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, m_szau_id, sizeof(m_szau_id), lau_idStatus, TRUE)

ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_szau_lname, sizeof(m_szau_lname), lau_lnameStatus, TRUE)

ADO_VARIABLE_LENGTH_ENTRY2(3, adVarChar, m_szau_fname, sizeof(m_szau_fname), lau_fnameStatus, TRUE)

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;

//Define Other variables


IADORecordBinding *picRs = NULL; // Interface Pointer declared.(VC++ Extensions)
CEmployeeRs emprs; // C++ class object

_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated


Security='SSPI';");

_bstr_t strMessage, strAuthorID;

int intRoyalty;
VARIANT vtRoyalty;

try {
// Open a Connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
hr = pConnection->Open(strCnn, "", "", adConnectUnspecified);
pConnection->CursorLocation = adUseClient;

// Open Command Object with one Parameter


TESTHR(pcmdByRoyalty.CreateInstance(__uuidof(Command)));
pcmdByRoyalty->CommandText = "byroyalty";
pcmdByRoyalty->CommandType = adCmdStoredProc;

// Get parameter value and append parameter


printf("Enter Royalty: ");
scanf_s("%d", &intRoyalty);

// 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;

// Create Recordset by executing the command


pcmdByRoyalty->ActiveConnection = pConnection;
pRstByRoyalty = pcmdByRoyalty->Execute(NULL, NULL, adCmdStoredProc);

// Open the authors table to get author names for display


TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));

// 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));

// Bind the Recordset to a C++ Class here


TESTHR(picRs->BindToRecordset(&emprs));

//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+"'";

printf("\n" "%s, %s %s",emprs.lau_idStatus == adFldOK ? emprs.m_szau_id : "<NULL>",\


emprs.lau_fnameStatus == adFldOK ? emprs.m_szau_fname : "<NULL>",\
emprs.lau_lnameStatus == adFldOK ? emprs.m_szau_lname : "<NULL>");
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);
}

// Clean up objects before exit. Release the IADORecordset Interface here


if (picRs)
picRs->Release();

if (pRstByRoyalty)
if (pRstByRoyalty->State == adStateOpen)
pRstByRoyalty->Close();
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;
long nCount = 0;
long i = 0;

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

Dim Cnxn As ADODB.Connection


Dim rstAuthors As ADODB.Recordset
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim fld As ADODB.Field
Dim strCnxn As String

Dim ix As Integer
Dim limit As Long
Dim Column(0 To 8) As Variant

Set Cnxn = New ADODB.Connection


Set rstAuthors = New ADODB.Recordset
Set cmd = New ADODB.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(7) = "zip"
Column(8) = "contract"

cmd.CommandText = "SELECT * FROM Authors WHERE state = ?"


Set prm = cmd.CreateParameter("ItemXparm", adChar, adParamInput, 2, "CA")
cmd.Parameters.Append prm
' set connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn
cmd.ActiveConnection = Cnxn
' open recordset
rstAuthors.Open cmd, , adOpenStatic, adLockReadOnly
'Connection and CommandType are omitted because
'a Command object is provided

Debug.Print "The Parameters collection accessed by index..."


Set prm = cmd.Parameters.Item(0)
Debug.Print "Parameter name = '"; prm.Name; "', value = '"; prm.Value; "'"
Debug.Print
Debug.Print

Debug.Print "The Parameters collection accessed by name..."


Set prm = cmd.Parameters.Item("ItemXparm")
Debug.Print "Parameter name = '"; prm.Name; "', value = '"; prm.Value; "'"
Debug.Print

Debug.Print "The Fields collection accessed by index..."

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

Debug.Print "The Fields collection accessed by name..."

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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

Set cmd = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If

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

Returns a Recordset whose rows represent the children of a collection Record.

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

Record Object (ADO) Recordset Object (ADO)


CursorType, LockType, and EditMode Properties
Example (VC++)
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.

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;

_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)));
hr = pConnection->Open(strCnn, "", "", adConnectUnspecified);

// Open recordset with data from employee table


TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));

pRstEmployees->CursorLocation = adUseClient;
pRstEmployees->CursorType = adOpenStatic;
pRstEmployees->LockType = adLockBatchOptimistic;

pRstEmployees->Open("employee", _variant_t((IDispatch *) pConnection,true),


adOpenStatic, adLockBatchOptimistic, adCmdTable);

// Show the EditMode property under different editing states.


// Show the EditMode property under different editing states.
pRstEmployees->AddNew ();
pRstEmployees->Fields->Item["emp_id"]->Value = (_bstr_t)("T-T55555M");
pRstEmployees->Fields->Item["fname"]->Value = (_bstr_t)("temp_fname");
pRstEmployees->Fields->Item["lname"]->Value = (_bstr_t)("temp_lname");
EditModeOutput("After AddNew: ", pRstEmployees->EditMode);

pRstEmployees->UpdateBatch(adAffectCurrent);
EditModeOutput("After Update: ", pRstEmployees->EditMode);

pRstEmployees->Fields->Item["fname"]->Value = (_bstr_t)("test");
EditModeOutput("After Edit: ", pRstEmployees->EditMode);

// Delete new record because this is a demonstration.


pConnection->Execute("DELETE FROM employee WHERE emp_id = 'T-T55555M'",
NULL, adCmdText);
}
catch(_com_error &e) {
// Display errors, if any. Pass connection pointer accessed from the Recordset.
PrintProviderError(pConnection);
PrintComError(e);
}

// Clean up objects before exit.


if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void EditModeOutput(char *strTemp, int intEditMode) {


// Print report based on the value of the EditMode property.
printf("\n%s", strTemp);
printf("\n EditMode = ");

switch (intEditMode) {
case adEditNone :
printf("adEditNone");
break;
case adEditInProgress :
printf("adEditInProgress");
break;
case adEditAdd :
printf("adEditAdd");
break;
}
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
// Print Com errors.
printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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

Represents a dynamic characteristic of an ADO object that is defined by the provider.

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

Specifies the group of records to be filtered from a Recordset.

CONSTANT VALUE DESCRIPTION

adFilterAffectedRecords 2 Filters for viewing only records affected


by the last Delete, Resync,
UpdateBatch, or CancelBatch call.

adFilterConflictingRecords 5 Filters for viewing the records that


failed the last batch update.

adFilterFetchedRecords 3 Filters for viewing the records in the


current cache-that is, the results of the
last call to retrieve records from the
database.

adFilterNone 0 Removes the current filter and restores


all records for viewing.

adFilterPendingRecords 1 Filters for viewing only records that


have changed but have not yet been
sent to the server. Applicable only for
batch update mode.

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

Loads the contents of an existing file into a Stream.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

' connection and recordset variables


Dim rstCompound As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim SQLCompound As String

Dim intCount As Integer

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open compound recordset


Set rstCompound = New ADODB.Recordset
SQLCompound = "SELECT * FROM Authors; " & _
"SELECT * FROM stores; " & _
"SELECT * FROM jobs"
rstCompound.Open SQLCompound, Cnxn, adOpenStatic, adLockReadOnly, adCmdText

' Display results from each SELECT statement


intCount = 1
Do Until rstCompound Is Nothing
Debug.Print "Contents of recordset #" & intCount

Do Until rstCompound.EOF
Debug.Print , rstCompound.Fields(0), rstCompound.Fields(1)
rstCompound.MoveNext
Loop

Set rstCompound = rstCompound.NextRecordset


intCount = intCount + 1
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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndNextRecordsetVB

See Also
NextRecordset Method (ADO )
Recordset Object (ADO )
Field Object
10/1/2018 • 2 minutes to read • Edit Online

Represents a column of data with a common data type.

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)

// Column title is the 1st field in the Recordset


ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar,m_szau_Title,
sizeof(m_szau_Title), lau_TitleStatus, FALSE)

// Column price is the 2nd field in the Recordset


ADO_VARIABLE_LENGTH_ENTRY2(2, adDouble, m_szau_Price,
sizeof(m_szau_Price), lau_PriceStatus, FALSE)

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;

// Define Other Variables


IADORecordBinding *picRs = NULL; // Interface Pointer Declared
CTitleRs titlers; // C++ Class Object
try {
// Assign Connection String to Variable
_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");

// Open Recordset containing the 10 most expensive titles in the Titles table.
TESTHR(pRstTemp.CreateInstance(__uuidof(Recordset)));

pRstTemp->MaxRecords = 10;

pRstTemp->Open("SELECT title,price FROM Titles ORDER BY Price DESC",


strCnn, adOpenForwardOnly, adLockReadOnly, adCmdText);

// Open IADORecordBinding interface pointer for binding Recordset to a class


TESTHR(pRstTemp->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Bind the Recordset to a C++ class here


TESTHR(picRs->BindToRecordset(&titlers));

// Display the contents of the Recordset


printf("Top Ten Titles by Price:\n\n");

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();

// 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;
}
}

// Clean up objects before exit. Release the IADORecordset Interface here


if (picRs)
picRs->Release();

if (pRstTemp)
if (pRstTemp->State == adStateOpen)
pRstTemp->Close();
};

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object
// pErr is a record object in the Connection's Error collection
ErrorPtr pErr = NULL;

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);
printf("\t Error Number :%x \t %s", pErr->Number, pErr->Description);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

Top Ten Titles by Price:


But Is It User Friendly? --- 22.95
Computer Phobic AND Non-Phobic Individuals: Behavior Variations --- 21.59
Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean --- 20.95
Secrets of Silicon Valley --- 20.00
The Busy Executive's Database Guide --- 19.99
Straight Talk About Computers --- 19.99
Silicon Valley Gastronomic Treats --- 19.99
Prolonged Data Deprivation: Four Case Studies --- 19.99
Sushi, Anyone? --- 14.99
Fifty Years in Buckingham Palace Kitchens --- 11.95

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

Dim rstEmployees As ADODB.Recordset


Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQLEmployees As String

Dim strOldFirst As String


Dim strOldLast As String
Dim strMessage As String
Dim strMarshalAll As String
Dim strMarshalModified As String

' Open connection


strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Set Cnxn = New ADODB.Connection
Cnxn.Open strCnxn

' open recordset with names from Employees table


' and set some properties through object refs
Set rstEmployees = New ADODB.Recordset
rstEmployees.CursorType = adOpenKeyset
rstEmployees.LockType = adLockOptimistic
rstEmployees.CursorLocation = adUseClient

strSQLEmployees = "SELECT fname, lname FROM Employee ORDER BY lname"

rstEmployees.Open strSQLEmployees, Cnxn, , , adCmdText


' empty properties have been set above

' Store original data


strOldFirst = rstEmployees!fname
strOldLast = rstEmployees!lname

' Change data in edit buffer


rstEmployees!fname = "Linda"
rstEmployees!lname = "Kobara"

' Show contents of buffer and get user input


strMessage = "Edit in progress:" & vbCr & _
" Original data = " & strOldFirst & " " & _
strOldLast & vbCr & " Data in buffer = " & _
rstEmployees!fname & " " & rstEmployees!lname & vbCr & vbCr & _
"Use Update to replace the original data with " & _
"the buffered data in the Recordset?"
strMarshalAll = "Would you like to send all the rows " & _
"in the recordset back to the server?"
strMarshalModified = "Would you like to send only " & _
strMarshalModified = "Would you like to send only " & _
"modified rows back to the server?"

If MsgBox(strMessage, vbYesNo) = vbYes Then


If MsgBox(strMarshalAll, vbYesNo) = vbYes Then
rstEmployees.MarshalOptions = adMarshalAll
rstEmployees.Update
ElseIf MsgBox(strMarshalModified, vbYesNo) = vbYes Then
rstEmployees.MarshalOptions = adMarshalModifiedOnly
rstEmployees.Update
End If
End If

' sShow the resulting data


MsgBox "Data in recordset = " & rstEmployees!fname & " " & _
rstEmployees!lname

' restore original data because this is a demonstration


If Not (strOldFirst = rstEmployees!fname And _
strOldLast = rstEmployees!lname) Then
rstEmployees!fname = strOldFirst
rstEmployees!lname = strOldLast
rstEmployees.Update
End If

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndMarshalOptionsVB

See Also
MarshalOptions Property (ADO )
MarshalOptionsEnum
GetRowsOptionEnum
10/1/2018 • 2 minutes to read • Edit Online

Specifies how many records to retrieve from a Recordset.

CONSTANT VALUE DESCRIPTION

adGetRowsRest -1 Retrieves the rest of the records in the


Recordset, from either the current
position or a bookmark specified by the
Start parameter of the GetRows
method.

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.

<!-- BeginFindJS -->


<%@ Language=JavaScript %>
<%// use this meta tag instead of adojavas.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->

<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">

<h1>ADO Recordset.Find Example</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 rsCustomers = Server.CreateObject("ADODB.Recordset");
// display string
var strMessage;
var strFind;

try
{
// open connection
Cnxn.Open(strCnxn);
Cnxn.Open(strCnxn);

//create recordset using object refs


SQLCustomers = "select * from Customers;";

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>

#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")

// 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';");

// Define ADO object pointers. Initialize pointers on define.


// These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
_CommandPtr pCmdChange = NULL;
_RecordsetPtr pRstTitles = NULL;

try {
// Open connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open (strCnn, "", "", adConnectUnspecified);

// Create command object.


TESTHR(pCmdChange.CreateInstance(__uuidof(Command)));
pCmdChange->ActiveConnection = pConnection;
pCmdChange->CommandText = strSQLChange;

// Open titles table, casting Connection pointer to an


// IDispatch type so converted to correct type of variant.
TESTHR(pRstTitles.CreateInstance(__uuidof(Recordset)));
pRstTitles->Open ("Titles", _variant_t((IDispatch *) pConnection, true),
adOpenStatic, adLockOptimistic, adCmdTable);
adOpenStatic, adLockOptimistic, adCmdTable);

// Print report of original data.


printf("\n\nData in Titles table before executing the query: \n");

// Call function to print loop recordset contents.


PrintOutput(pRstTitles);

// Clear extraneous errors from the Errors collection.


pConnection->Errors->Clear();

// Call ExecuteCommand subroutine to execute pCmdChange command.


ExecuteCommand(pCmdChange, pRstTitles);

// Print report of new data.


printf("\n\n\tData in Titles table after executing the query: \n");
PrintOutput(pRstTitles);

// Use Connection object's Execute method to execute SQL statement to restore data.
pConnection->Execute(strSQLRestore, NULL, adExecuteNoRecords);

// Retrieve the current data by requerying the recordset.


pRstTitles->Requery(adCmdUnknown);

// Print report of restored data.


printf("\n\n\tData after exec. query to restore original info: \n");
PrintOutput(pRstTitles);
}
catch (_com_error &e) {
PrintProviderError(pConnection);
PrintComError(e);
}

// Clean up objects before exit.


if (pRstTitles)
if (pRstTitles->State == adStateOpen)
pRstTitles->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void ExecuteCommand(_CommandPtr pCmdTemp, _RecordsetPtr pRstTemp) {


try {
// CommandText property already set before function was called.
pCmdTemp->Execute(NULL, NULL, adCmdText);

// Retrieve the current data by requerying the recordset.


pRstTemp->Requery(adCmdUnknown);
}

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);
}
}

void PrintOutput(_RecordsetPtr pRstTemp) {


// Ensure at top of recordset.
pRstTemp->MoveFirst();

// If EOF is true, then no data and skip print loop.


if ( pRstTemp->EndOfFile )
printf("\tRecordset empty\n");
else {
// Define strings for output conversions. Initialize to first record's values.
_bstr_t bstrTitle;
_bstr_t bstrType;
_bstr_t bstrType;

// Enumerate Recordset and print from each.


while ( !(pRstTemp->EndOfFile) ) {
// Convert variant string to convertable string type.
bstrTitle = pRstTemp->Fields->GetItem("Title")->Value;
bstrType = pRstTemp->Fields->GetItem("Type")->Value;
printf("\t%s, %s \n", (LPCSTR) bstrTitle, (LPCSTR) bstrType);

pRstTemp->MoveNext();
}
}
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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.

EVENT TRIGGERED IN CLONES?

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Dim Cnxn As ADODB.Connection


Dim rstEmployees As ADODB.Recordset
Dim fld As ADODB.Field
Dim strCnxn As String
Dim strSQLEmployee As String
Dim FieldType As String

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open recordset with data from Employees table


Set rstEmployees = New ADODB.Recordset
strSQLEmployee = "employee"
rstEmployees.Open strSQLEmployee, Cnxn, , , adCmdTable
'rstEmployees.Open strSQLEmployee, Cnxn, adOpenStatic, adLockReadOnly, adCmdTable
' the above two lines of code are identical

Debug.Print "Fields in Employees Table:" & vbCr

' Enumerate Fields collection of Employees table


For Each fld In rstEmployees.Fields
' translate field-type code to text
Select Case fld.Type
Case adChar
FieldType = "adChar"
Case adVarChar
FieldType = "adVarChar"
Case adSmallInt
FieldType = "adSmallInt"
Case adUnsignedTinyInt
FieldType = "adUnsignedTinyInt"
Case adDBTimeStamp
FieldType = "adDBTimeStamp"
End Select
' show results
Debug.Print " Name: " & fld.Name & vbCr & _
" Type: " & FieldType & vbCr
Next fld

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

Set fld = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndTypeFieldVB

Attribute VB_Name = "TypeField"

See Also
Field Object
Type Property (ADO )
Attributes Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Indicates one or more characteristics of an object.

Settings and Return Values


Sets or returns a Long value.
For a Connection object, the Attributes property is read/write, and its value can be the sum of one or more
XactAttributeEnum values. The default is zero (0).
For a Parameter object, the Attributes property is read/write, and its value can be the sum of any one or
more ParameterAttributesEnum values. The default is adParamSigned.
For a Field object, the Attributes property can be the sum of one or more FieldAttributeEnum values. It is
normally read-only. However, for new Field objects that have been appended to the Fields collection of a
Record, Attributes is read/write only after the Value property for the Field has been specified and the new
Field has been successfully added by the data provider by calling the Update method of the Fields collection.
For a Property object, the Attributes property is read-only, and its value can be the sum of any one or more
PropertyAttributesEnum values.

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

Connection Object (ADO) Field Object

Parameter Object Property Object (ADO)

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

Specifies the location of the cursor service.

CONSTANT VALUE DESCRIPTION

adUseClient 3 Uses client-side cursors supplied by a


local cursor library. Local cursor services
often will allow many features that
driver-supplied cursors may not, so
using this setting may provide an
advantage with respect to features that
will be enabled. For backward
compatibility, the synonym
adUseClientBatch is also supported.

adUseNone 1 Does not use cursor services. (This


constant is obsolete and appears solely
for the sake of backward compatibility.)

adUseServer 2 Default. Uses cursors supplied by the


data provider or driver. These cursors
are sometimes very flexible and allow
for additional sensitivity to changes
others make to the data source.
However, some features of the The
Microsoft Cursor Service for OLE DB,
such as disassociated

Recordset objects, cannot be simulated


with server-side cursors and these
features will be unavailable with this
setting.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection strings

Public Sub Main()


On Error GoTo ErrorHandler

'connection and recordset variables


Dim Cnxn As ADODB.Connection
Dim rstTitles As ADODB.Recordset
Dim strCnxn As String
Dim strSQLTitles As String

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open recordset using object refs to set properties


' that allow for updates to the database
Set rstTitles = New ADODB.Recordset
Set rstTitles.ActiveConnection = Cnxn
rstTitles.CursorType = adOpenKeyset
rstTitles.LockType = adLockOptimistic

strSQLTitles = "titles"
rstTitles.Open strSQLTitles

'rstTitles.Open strSQLTitles, Cnxn, adOpenKeyset, adLockPessimistic, adCmdTable


'the above line of code passes the same refs as the object refs listed above

' Change the type of the first title in the recordset


rstTitles!Type = "database"

' Display the results of the change


MsgBox "Before resync: " & vbCr & vbCr & _
"Title - " & rstTitles!Title & vbCr & _
"Type - " & rstTitles!Type

' Resync with database and redisplay results


rstTitles.Resync
MsgBox "After resync: " & vbCr & vbCr & _
"Title - " & rstTitles!Title & vbCr & _
"Type - " & rstTitles!Type

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndResyncVB

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

'recordset and connection variables


Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim rstTitles As ADODB.Recordset
Dim strSQLTitles As String
'record variables
Dim strTitle As String
Dim strMessage As String

' Open connection


strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Set Cnxn = New ADODB.Connection
Cnxn.Open strCnxn

' Open recordset dynamic to allow for changes


Set rstTitles = New ADODB.Recordset
strSQLTitles = "Titles"
rstTitles.Open strSQLTitles, Cnxn, adOpenDynamic, adLockPessimistic, adCmdTable

Cnxn.BeginTrans

' Loop through recordset and prompt user


' to change the type for a specified title

rstTitles.MoveFirst

Do Until rstTitles.EOF
If Trim(rstTitles!Type) = "psychology" Then
strTitle = rstTitles!Title
strMessage = "Title: " & strTitle & vbCr & _
"Change type to self help?"

' If yes, change type for the specified title


If MsgBox(strMessage, vbYesNo) = vbYes Then
rstTitles!Type = "self_help"
rstTitles.Update
End If
End If
rstTitles.MoveNext
Loop
' Prompt user to commit all changes made
If MsgBox("Save all changes?", vbYesNo) = vbYes Then
Cnxn.CommitTrans
Else
Cnxn.RollbackTrans
End If

' Print recordset


rstTitles.Requery
rstTitles.MoveFirst
Do While Not rstTitles.EOF
Debug.Print rstTitles!Title & " - " & rstTitles!Type
rstTitles.MoveNext
Loop

' Restore original data as this is a demo


rstTitles.MoveFirst

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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub

'EndBeginTransVB

See Also
BeginTrans, CommitTrans, and RollbackTrans Methods (ADO )
Connection Object (ADO )
AddNew Method (ADO)
10/1/2018 • 3 minutes to read • Edit Online

Creates a new record for an updatable Recordset object.

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.

create table aa1 (intf int, charf char(10))


insert into aa1 values (2, 'aa')

Dim cn As New adodb.Connection


Dim rs As New adodb.Recordset
Dim cmd As New adodb.Command

cn.ConnectionString = "Provider=SQLOLEDB;Data Source=alexverb2;uid=sa;pwd=foo$bar00;"

cn.Open
rs.Open "select * from xxx..aa1", cn, adOpenKeyset, adLockOptimistic

Dim fieldsArray(1) As Variant


fieldsArray(0) = "intf"
fieldsArray(1) = "charf"
Dim values(1) As Variant
values(0) = 4
values(1) = "as"
rs.AddNew fieldsArray, values
rs.Update

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;

// Define Other Variables


_bstr_t strMsg;
_variant_t vIndex;
int intLineCnt = 0;

try {
TESTHR(pRst.CreateInstance (__uuidof(Recordset)));

// Set the Recordset Cursor Location


pRst->CursorLocation = adUseClient;

for (short iIndex = 0; iIndex <= (pRst->Properties->GetCount() - 1);iIndex++) {


vIndex = iIndex;
pProperty = pRst->Properties->GetItem(vIndex);

int propType = (int)pProperty->GetType();

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++;

printf ("Property %d : %s,Type = %s\n",iIndex, (LPCSTR)pProperty->GetName(),


(LPCSTR)strMsg);
}
}
catch(_com_error &e) {
// Notify the user of errors if any.
PrintComError(e);
}
}

void PrintComError(_com_error &e) {

_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}
See Also
Property Object (ADO )
Type Property (ADO )
Optimize Property-Dynamic (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Specifies whether an index should be created on a field.

Settings and Return Values


Sets or returns a Boolean value that indicates whether an index should be created.

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

Indicates the size of the stream in number of bytes.

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"

// This Class extracts only fname,lname from employees table


class CEmployeeRs : public CADORecordBinding {

BEGIN_ADO_BINDING(CEmployeeRs)

// Column fname is the 1st field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, m_szemp_fname, sizeof(m_szemp_fname), lemp_fnameStatus, TRUE)

// Column lname is the 2nd field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_szemp_lname, sizeof(m_szemp_lname), lemp_lnameStatus, TRUE)

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;

// Define Other Variables


IADORecordBinding *picRs = NULL; // Interface Pointer declared
CEmployeeRs emprs; // C++ Class Object
CEmployeeRs emprs; // C++ Class Object
HRESULT hr = S_OK;
LPSTR strOldFirst = NULL;
LPSTR strOldLast = 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);

// Open an IADORecordBinding interface pointer which


// we'll use for Binding Recordset to a class.
TESTHR(pRstEmployees->QueryInterface( __uuidof(IADORecordBinding), (LPVOID*)&picRs) );

// Bind the Recordset to a C++ Class here.


TESTHR(picRs->BindToRecordset(&emprs));

// Store Original Data


strOldFirst = (LPSTR) malloc(sizeof(emprs.m_szemp_fname));
strOldLast = (LPSTR) malloc(sizeof(emprs.m_szemp_lname));

// Set the final character of the destination string to NULL.


strOldFirst[sizeof(emprs.m_szemp_fname)-1] = '\0';

// The source string will get truncated if its length is


// longer than the length of the destination string minus one.
strncpy_s(strOldFirst, sizeof(emprs.m_szemp_lname), strtok_s(emprs.m_szemp_fname, " ", &token1),
sizeof(emprs.m_szemp_fname) - 1);

// Set the final character of the destination string to NULL.


strOldLast[sizeof(emprs.m_szemp_lname) - 1] = '\0';

// The source string will get truncated if its length is


// longer than the length of the destination string minus one.
strncpy_s(strOldLast, sizeof(emprs.m_szemp_lname), strtok_s(emprs.m_szemp_lname," ", &token1),
sizeof(emprs.m_szemp_lname) - 1);

// 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);

// Set the final character of the destination string to NULL.


emprs.m_szemp_lname[sizeof(emprs.m_szemp_lname)-1] = '\0';

// 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);

// Show contents of buffer and get user input


printf("Edit in Progress:\n");
printf("Original Data = %s %s \n",strOldFirst,strOldLast);
printf("Data in buffer = %s %s \n", emprs.lemp_fnameStatus == adFldOK ? emprs.m_szemp_fname : "<NULL>",
emprs.lemp_lnameStatus == adFldOK ? emprs.m_szemp_lname : "
<NULL>");
printf("Use Update to replace the original data with the buffered data in the Recordset?\nEnter (y/n)
:?");
char opt1 = _getch();

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);
}
}

// Show the resulting data


printf("\nData In the Recordset = %s %s\n",
emprs.lemp_fnameStatus == adFldOK ?
emprs.m_szemp_fname : "<NULL>",
emprs.lemp_lnameStatus == adFldOK ?
emprs.m_szemp_lname : "<NULL>");

// Restore original data because this is a demonstration


if ((strcmp(strOldFirst,emprs.m_szemp_fname)) && (strcmp(strOldLast, emprs.m_szemp_lname))) {
// 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 get 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), strOldFirst,
sizeof(emprs.m_szemp_fname)-1);

// Set the final character of the destination string to NULL.


emprs.m_szemp_lname[sizeof(emprs.m_szemp_lname)-1] = '\0';

// The source string will get truncated if its length is


// longer than the length of the destination string minus one.
strncpy_s(emprs.m_szemp_lname, _countof(emprs.m_szemp_lname), strOldLast, sizeof(emprs.m_szemp_lname)
-1);
picRs->Update(&emprs);
}
}
catch(_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstEmployees->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;
}
}

// Clean up objects before exit.


// Deallocate memory
if (strOldFirst)
free(strOldFirst);
if (strOldLast)
free(strOldLast);

// Release the IADORecordset Interface here


if (picRs)
picRs->Release();
if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

See Also
MarshalOptions Property (ADO )
ADO Methods
1/25/2019 • 4 minutes to read • Edit Online

AddNew Creates a new record for an updatable Recordset object.

Append Appends an object to a collection. If the collection is Fields, a


new Field object may be created before it is appended to the
collection.

AppendChunk Appends data to a large text or binary data Field, or to a


Parameter object.

BeginTrans, CommitTrans, and RollbackTrans Manages 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 and ends the current


transaction. It may also start a new transaction.

Cancel Cancels execution of a pending, asynchronous method call.

CancelBatch Cancels a pending batch update.

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.

Clone Creates a duplicate Recordset object from an existing


Recordset object. Optionally, specifies that the clone be
read-only.

Close Closes an open object and any dependent objects.

CompareBookmarks Compares two bookmarks and returns an indication of their


relative values.

CopyRecord Copies a file or directory, and its contents, to another


location.

CopyTo Copies the specified number of characters or bytes


(depending on Type) in the Stream to another Stream
object.

CreateParameter Creates a new Parameter object that has the specified


properties.
Delete (ADO Parameters Collection) Deletes an object from the Parameters collection.

Delete (ADO Fields Collection) Deletes an object from the Fields collection.

Delete (ADO Recordset) Deletes the current record or a group of records.

DeleteRecord Deletes a file or directory, and all its subdirectories.

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.

Flush Forces the contents of the Stream remaining in the ADO


buffer to the underlying object with which the Stream is
associated.

get_OLEDBCommand Method Returns the underlying OLEDB Command, first propagating


any parameter information set on the ADO Command to the
OLEDB command.

GetChildren Returns a Recordset whose rows represent the files and


subdirectories in the directory represented by this Record.

GetChunk Returns all, or a portion of, the contents of a large text or


binary data Field object.

GetDataProviderDSO Method Retrieves the underlying OLEDB Data Source object from the
Shape provider.

GetRows Retrieves multiple records of a Recordset object into an


array.

GetString Returns the Recordset as a string.

LoadFromFile Loads the contents of an existing file into a Stream.

Move Moves the position of the current record in a Recordset


object.

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.

MoveRecord Moves a file, or a directory and its contents, to another


location.

NextRecordset Clears the current Recordset object and returns the next
Recordset by advancing through a series of commands.

Open (ADO Connection) Opens a connection to a data source.


Open (ADO Record) Opens an existing Record object, or creates a new file or
directory.

Open (ADO Recordset) Opens a cursor.

Open (ADO Stream) Opens a Stream object to manipulate streams of binary or


text data.

OpenSchema Obtains database schema information from the provider.

put_OLEDBCommand Method This method performs no operation - it always returns S_OK.

Read Reads a specified number of bytes from a Stream object.

ReadText Reads a specified number of characters from a text Stream


object.

Refresh Updates the objects in a collection to reflect objects available


from, and specific to, the provider.

Requery Updates the data in a Recordset object by re-executing the


query on which the object is based.

Resync Refreshes the data in the current Recordset object, or Fields


collection of a Record object, from the underlying database.

Save Saves the Recordset in a file or Stream object.

SaveToFile Saves the binary contents of a Stream to a file.

Seek 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.

SetEOS Sets the position that is the end of the stream.

SkipLine Skips one entire line when reading a text stream.

Stat Gets statistical information about an open stream.

Supports Determines whether a specified Recordset object supports a


particular type of functionality.

Update Saves any changes you make to the current row of a


Recordset object, or the Fields collection of a Record
object.

UpdateBatch Writes all pending batch updates to disk.

Write Writes binary data to a Stream object.


WriteText Writes a specified text string to a Stream object.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

'recordset and connection variables


Dim rstRoySched As ADODB.Recordset
Dim strSQLSched As String
Dim strCnxn As String
'record variables
Dim sngStart As Single
Dim sngEnd As Single
Dim sngNoCache As Single
Dim sngCache As Single
Dim intLoop As Integer
Dim strTemp As String

' Open the connection


strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"

' Open the RoySched Table


Set rstRoySched = New ADODB.Recordset
strSQLSched = "roysched"
rstRoySched.Open strSQLSched, strCnxn, , , adCmdTable

' Enumerate the Recordset object twice and


' record the elapsed time
sngStart = Timer

For intLoop = 1 To 2
rstRoySched.MoveFirst

If Not rstRoySched.EOF Then


' Execute a simple operation for the
' performance test
Do
strTemp = rstRoySched!title_id
rstRoySched.MoveNext
Loop Until rstRoySched.EOF
End If
Next intLoop

sngEnd = Timer
sngNoCache = sngEnd - sngStart

' Cache records in groups of 30 records.


rstRoySched.MoveFirst
rstRoySched.CacheSize = 30
sngStart = Timer

' Enumerate the Recordset object twice and record


' Enumerate the Recordset object twice and record
' the elapsed time
For intLoop = 1 To 2
rstRoySched.MoveFirst
Do While Not rstRoySched.EOF
' Execute a simple operation for the
' performance test
strTemp = rstRoySched!title_id
rstRoySched.MoveNext
Loop
Next intLoop

sngEnd = Timer
sngCache = sngEnd - sngStart

' Display performance results.


MsgBox "Caching Performance Results:" & vbCr & _
" No cache: " & Format(sngNoCache, "##0.000") & " seconds" & vbCr & _
" 30-record cache: " & Format(sngCache, "##0.000") & " seconds"

' 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

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndCacheSizeVB

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

public String getDescription()


public int getNativeError()
public int getNumber()
public String getSource()
public String getSQLState()

See Also
Error Object
EditMode Property
10/1/2018 • 2 minutes to read • Edit Online

Indicates the editing status of the current record.

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:

ActiveX Data Objects


ADO Collections
Command object
Connection object
Error object
Field object
Parameter object
Recordset object

Remote Data Service


DataSpace
ObjectProxy

See Also
Handling ADO Events
Microsoft ActiveX Data Objects (ADO )
Source Property (ADO Recordset)
10/1/2018 • 2 minutes to read • Edit Online

Indicates the data source for a Recordset object.

Settings and Return Values


Sets a String value or Command object reference; returns only a String value that indicates the source of the
Recordset.

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)

The Command object is not safe for scripting.


This section contains the following topic.
Command Object Properties, Methods, and Events

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

' connection and recordset variables


Dim rstEmployees As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strSQLEmployees As String
Dim strCnxn As String
' array variable
Dim arrEmployees As Variant
' detail variables
Dim strMessage As String
Dim intRows As Integer
Dim intRecord As Integer

' open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' open recordset client-side to enable RecordCount


Set rstEmployees = New ADODB.Recordset
strSQLEmployees = "SELECT fName, lName, hire_date FROM Employee ORDER BY lName"
rstEmployees.Open strSQLEmployees, Cnxn, adOpenStatic, adLockReadOnly, adCmdText

' get user input for number of rows


Do
strMessage = "Enter number of rows to retrieve:"
intRows = Val(InputBox(strMessage))

' if bad user input exit the loop


If intRows <= 0 Then
MsgBox "Please enter a positive number", vbOKOnly, "Not less than zero!"
' if number of requested records is over the total
ElseIf intRows > rstEmployees.RecordCount Then
MsgBox "Not enough records in Recordset to retrieve " & intRows & " rows.", _
vbOKOnly, "Over the available total"
Else
Exit Do
End If
Loop

' else put the data in an array and print


arrEmployees = rstEmployees.GetRows(intRows)
Dim x As Integer, y As Integer

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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndGetRowsVB

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

Dim Cnxn1 As ADODB.Connection


Dim Cnxn2 As ADODB.Connection
Dim cmdChange As ADODB.Command
Dim cmdRestore As ADODB.Command
Dim strCnxn As String
Dim strSQL As String

' Open two asynchronous connections, displaying


' a message while connecting
Set Cnxn1 = New ADODB.Connection
Set Cnxn2 = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"

Cnxn1.Open strCnxn, , , adAsyncConnect


Do Until Cnxn1.State <> adStateConnecting
Debug.Print "Opening first connection...."
Loop

Cnxn2.Open strCnxn, , , adAsyncConnect


Do Until Cnxn2.State <> adStateConnecting
Debug.Print "Opening second connection...."
Loop

' Create two command objects


Set cmdChange = New ADODB.Command
cmdChange.ActiveConnection = Cnxn1
strSQL = "UPDATE Titles SET type = 'self_help' WHERE type = 'psychology'"
cmdChange.CommandText = strSQL

Set cmdRestore = New ADODB.Command


cmdRestore.ActiveConnection = Cnxn2
strSQL = "UPDATE Titles SET type = 'psychology' WHERE type = 'self_help'"
cmdRestore.CommandText = strSQL

' Executing the commands, displaying a message


' while they are executing
cmdChange.Execute , , adAsyncExecute
Do Until cmdChange.State <> adStateExecuting
Debug.Print "Change command executing...."
Loop

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

If Not Cnxn2 Is Nothing Then


If Cnxn2.State = adStateOpen Then Cnxn2.Close
End If
Set Cnxn2 = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndStateVB

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"

// class extracts empid, fname and lastname


class CEmployeeRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CEmployeeRs)

// Column empid is the 1st field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, m_sz_empid, sizeof(m_sz_empid),
lemp_empidStatus, TRUE)

ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_sz_fname, sizeof(m_sz_fname),


lemp_fnameStatus, TRUE)

ADO_VARIABLE_LENGTH_ENTRY2(4, adVarChar, m_sz_lname, sizeof(m_sz_lname),


lemp_lnameStatus, TRUE)

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

inline int myscanf(char* strDest, int n) {


char strExBuff[10];
char* pstrRet = fgets(strDest, n, stdin);

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;

// Define Other variables


IADORecordBinding *picRs = NULL; // Interface Pointer declared.(VC++ Extensions)
CEmployeeRs emprs; // C++ class object

HRESULT hr = S_OK;

// Replace Data Source value with your server name.


_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");
_bstr_t strId;
_bstr_t strMessage;

try {
// Open a connection
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open(strCnn, "", "", adConnectUnspecified);

// Open employee table


TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));

// 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);

// Open IADORecordBinding interface pointer for Binding Recordset to a class


TESTHR(pRstEmployees->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Bind the Recordset to a C++ Class here


TESTHR(picRs->BindToRecordset(&emprs));

// 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 (strcmp(emprs.m_sz_empid, "") && strcmp(emprs.m_sz_fname, "") && strcmp(emprs.m_sz_lname, "")) {


// This adds a new record to the table
// if (FAILED(hr = picRs->AddNew(&emprs)))
//_com_issue_error(hr);
TESTHR(picRs->AddNew(&emprs));

// Show the newly added data


printf("New Record: %s %s %s \n",\
emprs.lemp_empidStatus == adFldOK ? emprs.m_sz_empid : "<NULL>",\
emprs.lemp_fnameStatus == adFldOK ? emprs.m_sz_fname : "<NULL>",\
emprs.lemp_lnameStatus == adFldOK ? emprs.m_sz_lname : "<NULL>");
}
else
printf("Please enter an employee id, first name and last name.\n");

// Delete the new record because this is a demonstration.


pConnection->Execute("DELETE FROM EMPLOYEE WHERE emp_id = '" + strId + "'", NULL, adCmdText);
}
catch(_com_error &e) {
// Notify the user of errors if any.
_variant_t vtConnect = pRstEmployees->GetActiveConnection();

// GetActiveConnection returns connect string if connection


// is not open, else returns Connection object.
switch(vtConnect.vt) {
case VT_BSTR:
printf("Error:\n");
printf("Code = %08lx\n", e.Error());
printf("Message = %s\n", e.ErrorMessage());
printf("Source = %s\n", (LPCSTR) e.Source());
printf("Description = %s\n", (LPCSTR) e.Description());
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}

// Clean up objects before exit. Release the IADORecordset Interface here


if (picRs)
picRs->Release();

if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;
long nCount = 0;
long i = 0;

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("\n\t Error number: %x\t%s", pErr->Number, (LPCSTR)pErr->Description);
}
}
}

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub NumericScaleX()

' connection and recordset variables


Dim rstDiscounts As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim fldTemp As ADODB.Field
Dim strCnxn As String
Dim strSQLDiscounts As String

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';Initial Catalog='Pubs';Integrated
Security='SSPI';"

Cnxn.Open strCnxn

' Open recordset


Set rstDiscounts = New ADODB.Recordset
strSQLDiscounts = "Discounts"
rstDiscounts.Open strSQLDiscounts, Cnxn, adOpenStatic, adLockReadOnly, adCmdTable

' Display numeric scale and precision of


' numeric and small integer fields
For Each fldTemp In rstDiscounts.Fields
If fldTemp.Type = adNumeric Or fldTemp.Type = adSmallInt Then
MsgBox "Field: " & fldTemp.Name & vbCr & _
"Numeric scale: " & _
fldTemp.NumericScale & vbCr & _
"Precision: " & fldTemp.Precision
End If
Next fldTemp

' 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

Retrieves information about a Stream object.

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

Indicates the type of locks placed on records during editing.

Settings and Return Values


Sets or returns a LockTypeEnum value. The default value is adLockReadOnly.

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

Specifies the attributes of a Property object.

CONSTANT VALUE DESCRIPTION

adPropNotSupported 0 Indicates that the property is not


supported by the provider.

adPropRequired 1 Indicates that the user must specify a


value for this property before the data
source is initialized.

adPropOptional 2 Indicates that the user does not need


to specify a value for this property
before the data source is initialized.

adPropRead 512 Indicates that the user can read the


property.

adPropWrite 1024 Indicates that the user can set the


property.

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

Creates a new Parameter object with the specified properties.

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

public static ObjectProxy DataSpace.createObject(String


progid, String connection)

Properties

public static int getInternetTimeout()


public static void setInternetTimeout(int plInetTimeout)

See Also
DataSpace Object (RDS )
ErrorValueEnum
11/28/2018 • 4 minutes to read • Edit Online

Specifies the type of ADO run-time error.


Three forms of the error number are listed:
Positive decimal-The low two bytes of the full number in decimal format. This number is displayed in the
default Visual Basic error message dialog box. For example, Run-time error '3707'.
Negative decimal-The decimal translation of the full error number.
Hexadecimal-The hexadecimal representation of the full error number. The Windows facility code is in the
fourth digit. The facility code for ADO error numbers is A. For example: 0x800A0E7B.

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.

CONSTANT VALUE DESCRIPTION

adErrBoundToCommand 3707 -2146824581 0x800A0E7B Cannot change the ActiveConnection


property of a Recordset object that
has a Command object as its source.

adErrCannotComplete 3732 -2146824556 0x800A0E94 Server cannot complete the operation.

adErrCantChangeConnection 3748 -2146824540 0x800A0EA4 Connection was denied. New


connection you requested has different
characteristics than the one already
being used.

adErrCantChangeProvider 3220 -2146825068 0X800A0C94 Supplied provider differs from the one
already being used.

adErrCantConvertvalue 3724 -2146824564 0x800A0E8C Data value cannot be converted for


reasons other than sign mismatch or
data overflow. For example, conversion
would have truncated data.

adErrCantCreate 3725 -2146824563 0x800A0E8D Data value cannot be set or retrieved


because the field data type was
unknown, or the provider had
insufficient resources to perform the
operation.

adErrCatalogNotSet 3747 -2146824541 0x800A0EA3 Operation requires a valid


ParentCatalog.

adErrColumnNotOnThisRow 3726 -2146824562 0x800A0E8E Record does not contain this field.
CONSTANT VALUE DESCRIPTION

adErrDataConversion 3421 -2146824867 0x800A0D5D Application uses a value of the wrong


type for the current operation.

adErrDataOverflow 3721 -2146824567 0x800A0E89 Data value is too large to be


represented by the field data type.

adErrDelResOutOfScope 3738 -2146824550 0x800A0E9A URL of the object to be deleted is


outside the scope of the current record.

adErrDenyNotSupported 3750 -2146824538 0x800A0EA6 Provider does not support sharing


restrictions.

adErrDenyTypeNotSupported 3751 -2146824537 0x800A0EA7 Provider does not support the


requested kind of sharing restriction.

adErrFeatureNotAvailable 3251 -2146825037 0x800A0CB3 Object or provider is not able to


perform requested operation.

adErrFieldsUpdateFailed 3749 -2146824539 0x800A0EA5 Fields update failed. For more


information, examine the Status
property of individual field objects.

adErrIllegalOperation 3219 -2146825069 0x800A0C93 Operation is not allowed in this context.

adErrIntegrityViolation 3719 -2146824569 0x800A0E87 Data value conflicts with the integrity
constraints of the field.

adErrInTransaction 3246 -2146825042 0x800A0CAE Connection object cannot be explicitly


closed while in a transaction.

adErrInvalidArgument 3001 -2146825287 0x800A0BB9 Arguments are of the wrong type, are
out of acceptable range, or are in
conflict with one another.

adErrInvalidConnection 3709 -2146824579 0x800A0E7D The connection cannot be used to


perform this operation. It is either
closed or invalid in this context.

adErrInvalidParamInfo 3708 -2146824580 0x800A0E7C Parameter object is incorrectly defined.


Inconsistent or incomplete information
was provided.

adErrInvalidTransaction 3714 -2146824574 0x800A0E82 Coordinating transaction is invalid or


has not started.

adErrInvalidURL 3729 -2146824559 0x800A0E91 URL contains invalid characters. Make


sure that the URL is typed correctly.

adErrItemNotFound 3265 -2146825023 0x800A0CC1 Item cannot be found in the collection


that corresponds to the requested
name or ordinal.
CONSTANT VALUE DESCRIPTION

adErrNoCurrentRecord 3021 -2146825267 0x800A0BCD Either BOF or EOF is True, or the


current record has been deleted.
Requested operation requires a current
record.

adErrNotExecuting 3715 -2146824573 0x800A0E83 Operation cannot be performed while


not executing.

adErrNotReentrant 3710 -2146824578 0x800A0E7E Operation cannot be performed while


processing event.

adErrObjectClosed 3704 -2146824584 0x800A0E78 Operation is not allowed when the


object is closed.

adErrObjectInCollection 3367 -2146824921 0x800A0D27 Object is already in collection. Cannot


append.

adErrObjectNotSet 3420 -2146824868 0x800A0D5C Object is no longer valid.

adErrObjectOpen 3705 -2146824583 0x800A0E79 Operation is not allowed when the


object is open.

adErrOpeningFile 3002 -2146825286 0x800A0BBA File could not be opened.

adErrOperationCancelled 3712 -2146824576 0x800A0E80 Operation has been canceled by the


user.

adErrOutOfSpace 3734 -2146824554 0x800A0E96 Operation cannot be performed.


Provider cannot obtain enough storage
space.

adErrPermissionDenied 3720 -2146824568 0x800A0E88 Insufficient permission prevents writing


to the field.

adErrProviderFailed 3000 -2146825288 0x800A0BB8 Provider did not perform the requested
operation.

adErrProviderNotFound 3706 -2146824582 0x800A0E7A Provider cannot be found. It may not


be correctly installed.

adErrReadFile 3003 -2146825285 0x800A0BBB File could not be read.

adErrResourceExists 3731 -2146824557 0x800A0E93 Copy operation cannot be performed.


Object named by destination URL
already exists. Specify
adCopyOverwrite to replace the
object.

adErrResourceLocked 3730 -2146824558 0x800A0E92 Object represented by the specified


URL is locked by one or more other
processes. Wait until the process has
finished and try the operation again.
CONSTANT VALUE DESCRIPTION

adErrResourceOutOfScope 3735 -2146824553 0x800A0E97 Source or destination URL is outside


the scope of the current record.

adErrSchemaViolation 3722 -2146824566 0x800A0E8A Data value conflicts with the data type
or constraints of the field.

adErrSignMismatch 3723 -2146824565 0x800A0E8B Conversion failed because the data


value was signed and the field data
type used by the provider was
unsigned.

adErrStillConnecting 3713 -2146824575 0x800A0E81 Operation cannot be performed while


connecting asynchronously.

adErrStillExecuting 3711 -2146824577 0x800A0E7F Operation cannot be performed while


executing asynchronously.

adErrTreePermissionDenied 3728 -2146824560 0x800A0E90 Permissions are insufficient to access


tree or subtree.

adErrUnavailable 3736 -2146824552 0x800A0E98 Operation did not complete and the
status is unavailable. The field may be
unavailable or the operation was not
attempted.

adErrUnsafeOperation 3716 -2146824572 0x800A0E84 Safety settings on this computer


prevent accessing a data source on
another domain.

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.

adErrVolumeNotFound 3733 -2146824555 0x800A0E95 Provider cannot locate the storage


device indicated by the URL. Make sure
that the URL is typed correctly.

adErrWriteFile 3004 -2146825284 0x800A0BBC Write to file failed.

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

Stream Property Read/Write. Gets/sets an OLE DB Stream object.

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

2. Query the IADOStreamConstruction interface on the Stream object:

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"

// This class extracts titles and type from Title table


class CTitleRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CTitleRs)

// Column title is the 2nd field in the table


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_szau_Title, sizeof(m_szau_Title), lau_TitleStatus, FALSE)

// Column type is the 3rd field in the table


ADO_VARIABLE_LENGTH_ENTRY2(3, adVarChar, m_szau_Type, sizeof(m_szau_Type), lau_TypeStatus, TRUE)
END_ADO_BINDING()

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;

// Define other Variables


HRESULT hr = S_OK;
IADORecordBinding *picRs = NULL; // Interface Pointer Declared
CTitleRs titlers; // C++ Class Object
LPSTR p_TempStr = NULL;
char * token1;
// Assign Connection String to Variable
_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");

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;

pRstTitles->Open("titles", _variant_t((IDispatch*) pConnection, true),


adOpenDynamic, adLockPessimistic, adCmdTable);

pConnection->BeginTrans();

// Display Connection Mode


if (pConnection->Mode == adModeShareExclusive)
printf("Connection Mode Is Exclusive");
else
printf("Connection Mode Is Not Exclusive");

// Display Isolation Level


if (pConnection->IsolationLevel == adXactIsolated)
printf("\nTransaction is Isolated\n");
else
printf("\nTransaction is not Isolated\n");

// Open an IADORecordBinding interface pointer which we will use for binding Recordset to a class.
TESTHR(pRstTitles->QueryInterface( __uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Bind the Recordset to a C++ class here


TESTHR(picRs->BindToRecordset(&titlers));

// Change the type of psychology titles.


p_TempStr = (LPSTR) malloc(sizeof(titlers.m_szau_Type));

while (!(pRstTitles->EndOfFile)) {
// Set the final character of the destination string to NULL.
p_TempStr[sizeof(titlers.m_szau_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(p_TempStr, sizeof(titlers.m_szau_Type), strtok_s(titlers.m_szau_Type, " ", &token1),
sizeof(titlers.m_szau_Type) - 1);

// Compare type with psychology


if (!strcmp(p_TempStr,"psychology")) {
// Set the final character of the destination string to NULL.
titlers.m_szau_Type[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();
}

// Print current data in recordset.


pRstTitles->Requery(adOptionUnspecified);

// Open again IADORecordBinding interface pointer for Binding


// Open again IADORecordBinding interface pointer for Binding
// Recordset to a class.
TESTHR(pRstTitles->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// ReBinding the Recordset to a C++ Class


TESTHR(picRs->BindToRecordset(&titlers));

// Move to the first record of the title table


pRstTitles->MoveFirst();

// Clear the screen for the next display


// system("cls");

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);
}

// Clean up objects before exit. Release the IADORecordset Interface here.


if (picRs)
picRs->Release();

if (pRstTitles)
if (pRstTitles->State == adStateOpen)
pRstTitles->Close();

if (pConnection)
if (pConnection->State == adStateOpen) {
// Restore Original Data
pConnection->RollbackTrans();

pConnection->Close();
}

// Deallocate the memory


if (p_TempStr)
free(p_TempStr);
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object
// pErr is a record object in the Connection's Error collection
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

Connection Mode Is Exclusive


Transaction is Isolated
The Busy Executive's Database Guide - business
Cooking with Computers: Surreptitious Balance Sheets - business
You Can Combat Computer Stress! - business
Straight Talk About Computers - business
Silicon Valley Gastronomic Treats - mod_cook
The Gourmet Microwave - mod_cook
The Psychology of Computer Cooking - UNDECIDED
But Is It User Friendly? - popular_comp
Secrets of Silicon Valley - popular_comp
Net Etiquette - popular_comp
Computer Phobic AND Non-Phobic Individuals: Behavior Variations - self_help
Is Anger the Enemy? - self_help
Life Without Fear - self_help
Prolonged Data Deprivation: Four Case Studies - self_help
Emotional Security: A New Algorithm - self_help
Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean - trad_cook
Fifty Years in Buckingham Palace Kitchens - trad_cook
Sushi, Anyone? - trad_cook

See Also
IsolationLevel Property
Mode Property (ADO )
GetString Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Returns the Recordset as a string.

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.

<!-- BeginMoveFirstVBS -->


<%@ Language=VBScript %>
<%' use this meta tag instead of adovbs.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->
<HTML>
<HEAD>
<TITLE>ADO MoveNext, MovePrevious, MoveLast, MoveFirst Methods</TITLE>

<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

' open connection


Set Cnxn = Server.CreateObject("ADODB.Connection")
strCnxn = "Provider='sqloledb';Data Source=" & _
Request.ServerVariables("SERVER_NAME") & ";" & _
"Integrated Security='SSPI';Initial Catalog='Northwind';"
Cnxn.Open strCnxn
' create and open Recordset using object refs
Set rsEmployees = Server.CreateObject("ADODB.Recordset")
strSQLEmployees = "Employees"

rsEmployees.ActiveConnection = Cnxn
rsEmployees.CursorLocation = adUseClient
rsEmployees.CursorType = adOpenKeyset
rsEmployees.LockType = adLockOptimistic
rsEmployees.Source = strSQLEmployees
rsEmployees.Open

rsEmployees.MoveFirst

If Not IsEmpty(Request.Form("MoveAction")) Then


strAction = Request.Form("MoveAction")
varPosition = Request.Form("Position")

rsEmployees.AbsolutePosition = varPosition

Select Case strAction

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

%>

<!-- Display Current Record Number and Recordset Size -->


<h2>Record Number <%=rsEmployees.AbsolutePosition%> of <%=rsEmployees.RecordCount%></H2>
<hr>
<table cellpadding=5 border=0>
<!-- BEGIN column header row for Customer Table-->
<tr>
<th>Name</th>
<th>Hire Date</th>
</tr>

<!--Display ADO Data from Customer Table-->


<tr>
<td><%= rsEmployees("LastName") & ", " %>
<%= rsEmployees("FirstName") & " " %></td>
<td><%= rsEmployees("HireDate")%></td>
</tr>
<tr>
<td colspan=2><%=strMessage%></td>
</tr>
</table>

<hr>

<form Name="Form" Method="Post" Action="MoveFirstVbs.asp">


<Input Type=Button Name=cmdDown Value="<">
<Input Type=Button Name=cmdUp Value=">">
<BR>
<H3>Click Direction Arrows to Use MovePrevious or MoveNext</H3>
<Input Type=Button Name=cmdFirst Value="First Record">
<Input Type=Button Name=cmdLast Value="Last Record">

<!-- Use Hidden Form Fields to record values to send to Server -->

<input Type="Hidden" Size="4" Name="MoveAction" Value="Move">


<input Type="Hidden" Size="4" Name="Position" Value="<%= rsEmployees.AbsolutePosition%>">
</form>

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

_variant_t GetChunk( long Length );

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;

unsigned char GetNumericScale( );


void PutNumericScale( unsigned char pbNumericScale );
__declspec(property(get=GetNumericScale,put=PutNumericScale)) unsigned
char NumericScale;

_variant_t GetOriginalValue( );
__declspec(property(get=GetOriginalValue)) _variant_t OriginalValue;

unsigned char GetPrecision( );


void PutPrecision( unsigned char pbPrecision );
__declspec(property(get=GetPrecision,put=PutPrecision)) unsigned char
Precision;

enum DataTypeEnum GetType( );


void PutType( enum DataTypeEnum pDataType );
__declspec(property(get=GetType,put=PutType)) enum DataTypeEnum Type;

_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.

CONSTANT VALUE DESCRIPTION

adDelayFetchFields 0x8000 Indicates to the provider that the fields


associated with the Record need not
be retrieved initially, but can be
retrieved at the first attempt to access
the field. The default behavior, indicated
by the absence of this flag, is to retrieve
all the Record object fields.

adDelayFetchStream 0x4000 Indicates to the provider that the


default stream associated with the
Record need not be retrieved initially.
The default behavior, indicated by the
absence of this flag, is to retrieve the
default stream associated with the
Record object.

adOpenAsync 0x1000 Indicates that the Record object is


opened in asynchronous mode.

adOpenExecuteCommand 0x10000 Indicates that the Source string


contains command text that should be
executed. This value is equivalent to the
adCmdText option on
Recordset.Open.

adOpenRecordUnspecified -1 Default. Indicates no options are


specified.

adOpenOutput 0x800000 Indicates that if the source points to a


node that contains an executable script
(such as an .ASP page), then the
opened Record will contain the results
of the executed script. This value is only
valid with non-collection records.

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

Specifies the level of transaction isolation for a Connection object.

CONSTANT VALUE DESCRIPTION

adXactUnspecified -1 Indicates that the provider is using a


different isolation level than specified,
but that the level cannot be
determined.

adXactChaos 16 Indicates that pending changes from


more highly isolated transactions
cannot be overwritten.

adXactBrowse 256 Indicates that from one transaction you


can view uncommitted changes in other
transactions.

adXactReadUncommitted 256 Same as adXactBrowse.

adXactCursorStability 4096 Indicates that from one transaction you


can view changes in other transactions
only after they have been committed.

adXactReadCommitted 4096 Same as adXactCursorStability.

adXactRepeatableRead 65536 Indicates that from one transaction you


cannot see changes made in other
transactions, but that requerying can
retrieve new Recordset objects.

adXactIsolated 1048576 Indicates that transactions are


conducted in isolation of other
transactions.

adXactSerializable 1048576 Same as adXactIsolated.

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

public int beginTrans()


public void commitTrans()
public void rollbackTrans()
public void cancel()
public void close()
public com.ms.wfc.data.Recordset execute(String commandText)
public com.ms.wfc.data.Recordset execute(String commandText, int options)
public int executeUpdate(String commandText)
public int executeUpdate(String commandText, int options)

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.

public void open()


public void open(String connectionString)
public void open(String connectionString, String userID)
public void open(String connectionString, String userID, String password)
public void open(String connectionString, String userID, String password, int options)
public Recordset openSchema(int schema, Object[]
restrictions, String schemaID)
public Recordset openSchema(int schema)
public Recordset openSchema(int schema, Object[] restrictions)

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.

public void addOnBeginTransComplete(ConnectionEventHandler handler)


public void removeOnBeginTransComplete(ConnectionEventHandler handler)
public void addOnCommitTransComplete(ConnectionEventHandler handler)
public void removeOnCommitTransComplete(ConnectionEventHandler handler)
public void addOnConnectComplete(ConnectionEventHandler handler)
public void removeOnConnectComplete(ConnectionEventHandler handler)
public void addOnDisconnect(ConnectionEventHandler handler)
public void removeOnDisconnect(ConnectionEventHandler handler)
public void addOnExecuteComplete(ConnectionEventHandler handler)
public void removeOnExecuteComplete(ConnectionEventHandler handler)
public void addOnInfoMessage(ConnectionEventHandler handler)
public void removeOnInfoMessage(ConnectionEventHandler handler)
public void addOnRollbackTransComplete(ConnectionEventHandler handler)
public void removeOnRollbackTransComplete(ConnectionEventHandler handler)
public void addOnWillConnect(ConnectionEventHandler handler)
public void removeOnWillConnect(ConnectionEventHandler handler)
public void addOnWillExecute(ConnectionEventHandler handler)
public void removeOnWillExecute(ConnectionEventHandler handler)

See Also
Connection Object (ADO )
Status Property (ADO Field)
10/1/2018 • 2 minutes to read • Edit Online

Indicates the status of a Field object.

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.

Recordset Field Status


Changes to the value of a Field object in the Fields collection of either a Recordset 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.

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;

// Define Other Variables


_variant_t index;
index.vt = VT_I2;

// Assign connection string to a variable.


_bstr_t strCnn("Provider='sqloledb';Data Source='(local)';Initial Catalog='pubs';Integrated
Security='SSPI';");

try {
// Open recordset from Authors table.
TESTHR(pRstCompound.CreateInstance(__uuidof(Recordset)));

// Pass the Cursor type and Lock type to the Recordset.


pRstCompound->Open("SELECT * FROM authors; SELECT * FROM stores;SELECT * FROM jobs",
strCnn, adOpenForwardOnly, adLockReadOnly, adCmdText);

// Display results from each SELECT statement.


int intCount = 1;
while (!(pRstCompound == NULL)) {
printf("\n\nContents of recordset #%d\n", intCount);

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;
}
}

// Clean up objects before exit.


if (pRstCompound)
if (pRstCompound->State == adStateOpen)
pRstCompound->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object. pErr is a record object in the Connection's Error
collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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

Saves the binary contents of a Stream to a file.

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.

Settings and Return Values


Sets or returns a DataTypeEnum value.

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

Field Object Parameter Object Property Object (ADO)

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.

Settings and Return Values


Sets or returns one or more of the ADCPROP_UPDATERESYNC_ENUM values.

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.

Settings and Return Values


Sets or returns a Long value that indicates, in seconds, how long to wait for the connection to open. Default is 15.

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.

CONSTANT VALUE DESCRIPTION

adOpenStreamAsync 1 Opens the Stream object in


asynchronous mode.

adOpenStreamFromRecord 4 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.
The default stream associated with that
node is opened.

adOpenStreamUnspecified -1 Default. Specifies opening the Stream


object with default options.

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

Obtains database schema information from the provider.

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

Reads a specified number of bytes from a binary Stream object.

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

Indicates the number of records in a Recordset object.

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

This example demonstrates the ActiveCommand property.


A subroutine is given a Recordset object whose ActiveCommand property is used to display the command text
and parameter that created the Recordset.

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"

// Class extracts lname,fname from authors table.


class CAuthorsRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CAuthorsRs)

// Column lname is the 2nd field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_szau_lname,
sizeof(m_szau_lname), lau_lnameStatus, TRUE)

// Column fname is the 3rd field in the recordset.


ADO_VARIABLE_LENGTH_ENTRY2(3, adVarChar, m_szau_fname,
sizeof(m_szau_fname), lau_fnameStatus, TRUE)

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

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 {
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;

// Definitions of other variables


_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");
_bstr_t strPrompt;
_bstr_t strName;
CHAR strcharName[50];

try {
// Open connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
TESTHR(pCmd.CreateInstance(__uuidof(Command)));

printf ("ActiveCommandX Example\n\n");


strPrompt = "Enter an author's name (e.g., Ringer): ";
printf(strPrompt);
mygets(strcharName, 50);
char *tempStr = strtok_s(strcharName, " \t", &token1);
strName = tempStr;

pCmd->CommandText = "SELECT * FROM authors WHERE au_lname = ?";


pCmd->Parameters->Append(pCmd->CreateParameter("LastName", adChar, adParamInput, 20, strName));

pConnection->Open (strCnn, "", "", adConnectUnspecified);


pCmd->PutActiveConnection(_variant_t((IDispatch*)pConnection));
pRstAuthors = pCmd->Execute(NULL, NULL, adCmdText);
ActiveCommandXprint(pRstAuthors);
} // End Try statement.
catch(_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
PrintProviderError(pConnection);
PrintComError(e);
}

// Clean up objects before exit.


if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void ActiveCommandXprint(_RecordsetPtr pRst = NULL) {


// Varible Declaraion & initialization
IADORecordBinding *picRs = NULL; // Interface Pointer declared.
IADORecordBinding *picRs = NULL; // Interface Pointer declared.
CAuthorsRs autrs; // C++ class object
_bstr_t strName;

// Open an IADORecordBinding interface pointer which


// we'll use for Binding Recordset to a class
TESTHR(pRst->QueryInterface(__uuidof(IADORecordBinding),(LPVOID*)&picRs));

// Bind the Recordset to a C++ Class here


TESTHR(picRs->BindToRecordset(&autrs));

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 {

printf ("Name = '%s %s'",


autrs.lau_fnameStatus == adFldOK ? autrs.m_szau_fname : "<NULL>",
autrs.lau_lnameStatus == adFldOK ? autrs.m_szau_lname : "<NULL>");
}

// Release IADORecordset Interface


if (picRs)
picRs->Release();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;
long nCount = 0;
long i = 0;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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

Specifies the direction of a record search within a Recordset.

CONSTANT VALUE DESCRIPTION

adSearchBackward -1 Searches backward, stopping at the


beginning of the Recordset. If a match
is not found, the record pointer is
positioned at BOF.

adSearchForward 1 Searches forward, stopping at the end


of the Recordset. If a match is not
found, the record pointer is positioned
at EOF.

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.

Connection Dynamic Properties


ADO PROPERTY NAME OLE DB PROPERTY NAME

Active Sessions DBPROP_ACTIVESESSIONS

Asynchable Abort DBPROP_ASYNCTXNABORT

Asynchable Commit DBPROP_ASYNCTNXCOMMIT

Autocommit Isolation Levels DBPROP_SESS_AUTOCOMMITISOLEVELS

Catalog Location DBPROP_CATALOGLOCATION

Catalog Term DBPROP_CATALOGTERM

Column Definition DBPROP_COLUMNDEFINITION

Connect Timeout DBPROP_INIT_TIMEOUT

Current Catalog DBPROP_CURRENTCATALOG

Data Source DBPROP_INIT_DATASOURCE

Data Source Name DBPROP_DATASOURCENAME

Data Source Object Threading Model DBPROP_DSOTHREADMODEL

DBMS Name DBPROP_DBMSNAME

DBMS Version DBPROP_DBMSVER

Extended Properties DBPROP_INIT_PROVIDERSTRING


ADO PROPERTY NAME OLE DB PROPERTY NAME

GROUP BY Support DBPROP_GROUPBY

Heterogeneous Table Support DBPROP_HETEROGENEOUSTABLES

Identifier Case Sensitivity DBPROP_IDENTIFIERCASE

Initial Catalog DBPROP_INIT_CATALOG

Isolation Levels DBPROP_SUPPORTEDTXNISOLEVELS

Isolation Retention DBPROP_SUPPORTEDTXNISORETAIN

Locale Identifier DBPROP_INIT_LCID

Location DBPROP_INIT_LOCATION

Maximum Index Size DBPROP_MAXINDEXSIZE

Maximum Row Size DBPROP_MAXROWSIZE

Maximum Row Size Includes BLOB DBPROP_MAXROWSIZEINCLUDESBLOB

Maximum Tables in SELECT DBPROP_MAXTABLESINSELECT

Mode DBPROP_INIT_MODE

Multiple Parameter Sets DBPROP_MULTIPLEPARAMSETS

Multiple Results DBPROP_MULTIPLERESULTS

Multiple Storage Objects DBPROP_MULTIPLESTORAGEOBJECTS

Multi-Table Update DBPROP_MULTITABLEUPDATE

NULL Collation Order DBPROP_NULLCOLLATION

NULL Concatenation Behavior DBPROP_CONCATNULLBEHAVIOR

OLE DB Services DBPROP_INIT_OLEDBSERVICES

OLE DB Version DBPROP_PROVIDEROLEDBVER

OLE Object Support DBPROP_OLEOBJECTS

Open Rowset Support DBPROP_OPENROWSETSUPPORT

ORDER BY Columns in Select List DBPROP_ORDERBYCOLUMNSINSELECT

Output Parameter Availability DBPROP_OUTPUTPARAMETERAVAILABILITY


ADO PROPERTY NAME OLE DB PROPERTY NAME

Pass By Ref Accessors DBPROP_BYREFACCESSORS

Password DBPROP_AUTH_PASSWORD

Persist Security Info DBPROP_AUTH_PERSIST_SENSITIVE_AUTHINFO

Persistent ID Type DBPROP_PERSISTENTIDTYPE

Prepare Abort Behavior DBPROP_PREPAREABORTBEHAVIOR

Prepare Commit Behavior DBPROP_PREPARECOMMITBEHAVIOR

Procedure Term DBPROP_PROCEDURETERM

Prompt DBPROP_INIT_PROMPT

Provider Friendly Name DBPROP_PROVIDERFRIENDLYNAME

Provider Name DBPROP_PROVIDERFILENAME

Provider Version DBPROP_PROVIDERVER

Read-Only Data Source DBPROP_DATASOURCEREADONLY

Rowset Conversions on Command DBPROP_ROWSETCONVERSIONSONCOMMAND

Schema Term DBPROP_SCHEMATERM

Schema Usage DBPROP_SCHEMAUSAGE

SQL Support DBPROP_SQLSUPPORT

Structured Storage DBPROP_STRUCTUREDSTORAGE

Subquery Support DBPROP_SUBQUERIES

Table Term DBPROP_TABLETERM

Transaction DDL DBPROP_SUPPORTEDTXNDDL

User ID DBPROP_AUTH_USERID

User Name DBPROP_USERNAME

Window Handle DBPROP_INIT_HWND

Recordset Dynamic Properties


Note that the Dynamic Properties of the Recordset object go out of scope (become unavailable) when the
Recordset is closed.
ADO PROPERTY NAME OLE DB PROPERTY NAME

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

Access Order DBPROP_ACCESSORDER

Append-Only Rowset DBPROP_APPENDONLY

Asynchronous Rowset Processing DBPROP_ROWSET_ASYNCH

Auto Recalc DBPROP_ADC_AUTORECALC

Background Fetch Size DBPROP_ASYNCHFETCHSIZE

Background Thread Priority DBPROP_ASYNCHTHREADPRIORITY

Batch Size DBPROP_ADC_BATCHSIZE

Blocking Storage Objects DBPROP_BLOCKINGSTORAGEOBJECTS

Bookmark Type DBPROP_BOOKMARKTYPE

Bookmarkable DBPROP_IROWSETLOCATE

Bookmarks Ordered DBPROP_ORDEREDBOOKMARKS

Cache Child Rows DBPROP_ADC_CACHECHILDROWS

Cache Deferred Columns DBPROP_CACHEDEFERRED

Change Inserted Rows DBPROP_CHANGEINSERTEDROWS

Column Privileges DBPROP_COLUMNRESTRICT

Column Set Notification DBPROP_NOTIFYCOLUMNSET

Column Writable DBPROP_MAYWRITECOLUMN

Command Time Out DBPROP_COMMANDTIMEOUT

Cursor Engine Version DBPROP_ADC_CEVER

Defer Column DBPROP_DEFERRED

Delay Storage Object Updates DBPROP_DELAYSTORAGEOBJECTS

Fetch Backwards DBPROP_CANFETCHBACKWARDS

Filter Operations DBPROP_FILTERCOMPAREOPS

Find Operations DBPROP_FINDCOMPAREOPS


ADO PROPERTY NAME OLE DB PROPERTY NAME

Hidden Columns (Count) DBPROP_HIDDENCOLUMNS

Hold Rows DBPROP_CANHOLDROWS

Immobile Rows DBPROP_IMMOBILEROWS

Initial Fetch Size DBPROP_ASYNCHPREFETCHSIZE

Literal Bookmarks DBPROP_LITERALBOOKMARKS

Literal Row Identity DBPROP_LITERALIDENTITY

Maintain Change Status DBPROP_ADC_MAINTAINCHANGESTATUS

Maximum Open Rows DBPROP_MAXOPENROWS

Maximum Pending Rows DBPROP_MAXPENDINGROWS

Maximum Rows DBPROP_MAXROWS

Memory Usage DBPROP_MEMORYUSAGE

Notification Granularity DBPROP_NOTIFICATIONGRANULARITY

Notification Phases DBPROP_NOTIFICATIONPHASES

Objects Transacted DBPROP_TRANSACTEDOBJECT

Others' Changes Visible DBPROP_OTHERUPDATEDELETE

Others' Inserts Visible DBPROP_OTHERINSERT

Own Changes Visible DBPROP_OWNUPDATEDELETE

Own Inserts Visible DBPROP_OWNINSERT

Preserve on Abort DBPROP_ABORTPRESERVE

Preserve on Commit DBPROP_COMMITPRESERVE

Private1

Quick Restart DBPROP_QUICKRESTART

Reentrant Events DBPROP_REENTRANTEVENTS

Remove Deleted Rows DBPROP_REMOVEDELETED

Report Multiple Changes DBPROP_REPORTMULTIPLECHANGES


ADO PROPERTY NAME OLE DB PROPERTY NAME

Reshape Name DBPROP_ADC_RESHAPENAME

Resync Command DBPROP_ADC_CUSTOMRESYNCH

Return Pending Inserts DBPROP_RETURNPENDINGINSERTS

Row Delete Notification DBPROP_NOTIFYROWDELETE

Row First Change Notification DBPROP_NOTIFYROWFIRSTCHANGE

Row Insert Notification DBPROP_NOTIFYROWINSERT

Row Privileges DBPROP_ROWRESTRICT

Row Resynchronization Notification DBPROP_NOTIFYROWRESYNCH

Row Threading Model DBPROP_ROWTHREADMODEL

Row Undo Change Notification DBPROP_NOTIFYROWUNDOCHANGE

Row Undo Delete Notification DBPROP_NOTIFYROWUNDODELETE

Row Undo Insert Notification DBPROP_NOTIFYROWUNDOINSERT

Row Update Notification DBPROP_NOTIFYROWUPDATE

Rowset Fetch Position Change Notification DBPROP_NOTIFYROWSETFETCHPOSITIONCHANGE

Rowset Release Notification DBPROP_NOTIFYROWSETRELEASE

Scroll Backwards DBPROP_CANSCROLLBACKWARDS

Server Cursor DBPROP_SERVERCURSOR

Skip Deleted Bookmarks DBPROP_BOOKMARKSKIPPED

Strong Row Identity DBPROP_STRONGIDENTITY

Unique Catalog DBPROP_ADC_UNIQUECATALOG

Unique Rows DBPROP_UNIQUEROWS

Unique Schema DBPROP_ADC_UNIQUESCHEMA

Unique Table DBPROP_ADC_UNIQUETABLE

Updatability DBPROP_UPDATABILITY

Update Criteria DBPROP_ADC_UPDATECRITERIA


ADO PROPERTY NAME OLE DB PROPERTY NAME

Update Resync DBPROP_ADC_UPDATERESYNC

Use Bookmarks DBPROP_BOOKMARKS


Property (Visual C++ Syntax Index with #import)
10/1/2018 • 2 minutes to read • Edit Online

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;

enum DataTypeEnum GetType( );


__declspec(property(get=GetType)) enum DataTypeEnum Type;

_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.

Settings and Return Values


Sets or returns a ConnectModeEnum value. The default value for a Connection is adModeUnknown. The
default value for a Record object is adModeRead. The default value for a Stream associated with an
underlying source (opened with a URL as the source, or as the default Stream of a Record) is adModeRead.
The default value for a Stream not associated with an underlying source (instantiated in memory) is
adModeUnknown.

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

Connection Object (ADO) Record Object (ADO) Stream Object (ADO)

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

Indicates a filter for data in a Recordset.

Settings and Return Values


Sets or returns a Variant value, which can contain one of the following items:
Criteria string: A string made up of one or more individual clauses concatenated with AND or OR
operators.
Array of bookmarks: An array of unique bookmark values that point to records in the Recordset
object.
A FilterGroupEnum value.

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:

The filtering was based on non-key fields in a single-keyed table.


The filtering was based on any fields in a multiple-keyed table.
Modifications were made on non-key fields in a single-keyed table.
Modifications were made on any fields in a multiple-keyed table.
The following table summarizes the effects of adFilterPendingRecords in different combinations of filtering
and modifications. The left column shows the possible modifications. Modifications can be made on any of
the non-keyed fields, on the key field in a single-keyed table, or on any of the key fields in a multiple-keyed
table. The top row shows the filtering criterion. Filtering can be based on any of the non-keyed fields, the key
field in a single-keyed table, or any of the key fields in a multiple-keyed table. The intersecting cells show the
results. A + plus sign means that applying adFilterPendingRecords results in a non-empty Recordset. A -
minus sign means an empty Recordset.

NON KEYS SINGLE KEY MULTIPLE KEYS

Non keys + + +

Single Key + - N/A

Multiple Keys + N/A +

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>

#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")

// 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;

// Temporary string variable for type conversion for printing.


_bstr_t bstrFName;
_bstr_t bstrLName;

try {
// Open recordset from Authors table.
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
pRstAuthors->CursorType = adOpenStatic;

// Use client cursor to enable AbsolutePosition property.


pRstAuthors->CursorLocation = adUseClient;
pRstAuthors->Open("Authors", strCnn, adOpenStatic, adLockBatchOptimistic, adCmdTable);

// Show current record information and get user's method choice.


while (true) { // Continuous loop.
// Convert variant string to convertable string type.
bstrFName = pRstAuthors->Fields->Item["au_fName"]->Value;
bstrLName = pRstAuthors->Fields->Item["au_lName"]->Value;

printf("Name: %s %s\n Record %d of %d\n\n",


printf("Name: %s %s\n Record %d of %d\n\n",
(LPCSTR) bstrFName,
(LPCSTR) bstrLName,
pRstAuthors->AbsolutePosition,
pRstAuthors->RecordCount);
printf("[1 - MoveFirst, 2 - MoveLast, \n");
printf(" 3 - MoveNext, 4 - MovePrevious, 5 - Quit]\n");

scanf_s("%d", &intCommand);

if ((intCommand < 1) || (intCommand > 4))


break; // Out of range entry exits program loop.

// Call method based on user's input.


MoveAny(intCommand, pRstAuthors);
}
}
catch (_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstAuthors->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;
}
}

// Clean up objects before exit.


if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
}

void MoveAny(int intChoice, _RecordsetPtr pRstTemp) {


// Use specified method, trapping for BOF and EOF
try {
switch(intChoice) {
case 1:
pRstTemp->MoveFirst();
break;
case 2:
pRstTemp->MoveLast();
break;
case 3:
pRstTemp->MoveNext();
if (pRstTemp->EndOfFile) {
printf("\nAlready at end of recordset!\n");
pRstTemp->MoveLast();
} // End If
break;
case 4:
pRstTemp->MovePrevious();
if (pRstTemp->BOF) {
printf("\nAlready at beginning of recordset!\n");
pRstTemp->MoveFirst();
}
break;
default:
;
}
}
}

catch(_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstTemp->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;
}
}
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.

// pErr is a record object in the Connection's Error collection.


ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

Input

See Also
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods (ADO )
Recordset Object (ADO )
ParameterAttributesEnum
10/1/2018 • 2 minutes to read • Edit Online

Specifies the attributes of a Parameter object.

CONSTANT VALUE DESCRIPTION

adParamSigned 16 Indicates that the parameter accepts


signed values.

adParamNullable 64 Indicates that the parameter accepts


null values.

adParamLong 128 Indicates that the parameter accepts


long binary data.

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;

// Define Other Variables


_bstr_t strCmdChange;
_bstr_t strCmdRestore;
BOOL booChanged = FALSE;

_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);

// Define command strings.


strCmdChange = "UPDATE titles SET type = 'self_help' WHERE type = 'psychology'";

strCmdRestore = "UPDATE titles SET type = 'psychology' WHERE type = 'self_help'";

// Begin a transaction, then execute a command asynchronously.


pConnection->BeginTrans();
pConnection->Execute(strCmdChange, NULL, adAsyncExecute);

// do something else for a little while - this could be changed


for ( int i = 1 ; i <= 100000 ; i++ )
printf("%d\n", i);

// 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);
}

// Cleanup object before exit


if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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

public void appendChunk(byte[] bytes)


public void appendChunk(char[] chars)
public void appendChunk(String chars)
public byte[] getByteChunk(int len)
public char[] getCharChunk(int len)
public String getStringChunk(int len)

Properties

public int getActualSize()


public int getAttributes()
public void setAttributes(int pl)
public com.ms.com.IUnknown getDataFormat()
public void setDataFormat(com.ms.com.IUnknown format)

(For more information, see the documentation for the com.ms.wfc.data.IDataFormat interface.)

public int getDefinedSize()


public void setDefinedSize(int pl)
public String getName()
public int getNumericScale()
public void setNumericScale(byte pbNumericScale)
public Variant getOriginalValue()
public int getPrecision()
public void setPrecision(byte pbPrecision)
public int getType()
public void setType(int pDataType)
public Variant getUnderlyingValue()
public Variant getValue()
public void setValue(Variant value)
public AdoProperties getProperties()

Field Accessor Methods


The Value property of a Field object gets or sets the content of that object. The content is represented as a
VARIANT, a type of object that can be assigned a value and any of several data types.
ADO/WFC implements the Value property with the getValue method, which returns a VARIANT object; and the
setValue method, which takes a VARIANT as an argument. VARIANTs are highly efficient in certain languages,
such as Microsoft Visual Basic.
In addition to the Value property, ADO/WFC provides accessor methods that use Java data types to get and set
the content of Field objects. Most of these methods have names of the form getDataType or setDataType.
There are two noteworthy exceptions: One of the getObject methods returns an object coerced into a specified
class. There is no getNull property; instead, there is an isNull property that returns a Boolean value indicating
whether the field is null.
public native boolean getBoolean();
public void setBoolean(boolean v)
public native byte getByte();
public void setByte(byte v)
public native byte[] getBytes();
public void setBytes(byte[] v)
public native double getDouble();
public void setDouble(double v)
public native float getFloat();
public void setFloat(float v)
public native int getInt();
public void setInt(int v)
public native long getLong();
public void setLong(long v)
public native short getShort();
public void setShort(short v)
public native String getString();
public void setString(String v)
public native boolean isNull();
public void setNull()
public Object getObject()
public Object getObject(Class c)
public void setObject(Object value)

See Also
Field Object
EventReasonEnum
10/1/2018 • 2 minutes to read • Edit Online

Specifies the reason that caused an event to occur.

CONSTANT VALUE DESCRIPTION

adRsnAddNew 1 An operation added a new record.

adRsnClose 9 An operation closed the Recordset.

adRsnDelete 2 An operation deleted a record.

adRsnFirstChange 11 An operation made the first change to


a record.

adRsnMove 10 An operation moved the record pointer


within the Recordset.

adRsnMoveFirst 12 An operation moved the record pointer


to the first record in the Recordset.

adRsnMoveLast 15 An operation moved the record pointer


to the last record in the Recordset.

adRsnMoveNext 13 An operation moved the record pointer


to the next record in the Recordset.

adRsnMovePrevious 14 An operation moved the record pointer


to the previous record in the
Recordset.

adRsnRequery 7 An operation requeried the Recordset.

adRsnResynch 8 An operation resynchronized the


Recordset with the database.

adRsnUndoAddNew 5 An operation reversed the addition of a


new record.

adRsnUndoDelete 6 An operation reversed the deletion of a


record.

adRsnUndoUpdate 4 An operation reversed the update of a


record.

adRsnUpdate 3 An operation updated an existing


record.

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

WillChangeRecord and RecordChangeComplete Events (ADO) WillChangeRecordset and RecordsetChangeComplete Events


(ADO)

WillMove and MoveComplete Events (ADO)


Rowset Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online

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)

// Column empid is the 1st field in the recordset

ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, m_sz_titleid,


sizeof(m_sz_titleid), lemp_titleidStatus, TRUE)

ADO_VARIABLE_LENGTH_ENTRY2(2, adInteger, m_sz_lorange,


sizeof(m_sz_lorange), lemp_lorangeStatus, TRUE)

ADO_VARIABLE_LENGTH_ENTRY2(3, adInteger, m_sz_hirange,


sizeof(m_sz_hirange), lemp_hirangeStatus, TRUE)

ADO_VARIABLE_LENGTH_ENTRY2(4, adInteger, m_sz_royalty,


sizeof(m_sz_royalty), lemp_royaltyStatus, TRUE)

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;

// Define Other Variables


IADORecordBinding *picRs = NULL; // Interface Pointer declared.
CRoySchedRs royschrs; // C++ class object

char strTitleID[10], strTmpTitleID[10] = "";


long longHiRange = 0;
int intRoyalty = 0, intLoRange = 0, cnt = 0;
bool blnFound = TRUE;

_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated


Security='SSPI';");

try {
// Open RoySched table
TESTHR(pRstRoySched.CreateInstance(__uuidof(Recordset)));

pRstRoySched->CursorLocation = adUseClient;
pRstRoySched->CursorType = adOpenStatic;
pRstRoySched->LockType = adLockBatchOptimistic;

TESTHR(pRstRoySched->Open("SELECT * FROM roysched WHERE royalty = 20",


strCnn, adOpenStatic, adLockBatchOptimistic, adCmdText));

// Prompt for a record to delete.


printf("Before delete there are %d titles with 20 percent royalty :\n",
pRstRoySched->RecordCount);

// Open an IADORecordBinding interface pointer for Binding Recordset to a class.


TESTHR(pRstRoySched->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Bind the Recordset to a C++ Class here


TESTHR(picRs->BindToRecordset(&royschrs));

while(!(pRstRoySched->EndOfFile)) {
printf("%s\n", royschrs.lemp_titleidStatus == adFldOK ?
royschrs.m_sz_titleid : "<NULL>");
pRstRoySched->MoveNext();
}

printf("\nEnter the ID of a record to delete: ");


mygets(strTitleID, 10);

// Converting the title_id to upper case


for ( cnt = 0 ; cnt < 10 ; cnt++ )
if ( strTitleID[cnt] != NULL )
if ( IsCharAlpha( strTitleID[cnt]) )
if ( islower( strTitleID[cnt]) )
strTmpTitleID[cnt] = _toupper(strTitleID[cnt]);
else
strTmpTitleID[cnt] = strTitleID[cnt];
else
strTmpTitleID[cnt] = strTitleID[cnt];

// Move to the record and save data so it can be restored.


pRstRoySched->PutFilter ("title_id = '" +
(_bstr_t)(LPCSTR)strTmpTitleID + "'");

if ( pRstRoySched->RecordCount != 0 ) {
intLoRange = royschrs.m_sz_lorange;
longHiRange = royschrs.m_sz_hirange;
intRoyalty = royschrs.m_sz_royalty;

// Delete the record


pRstRoySched->Delete(adAffectCurrent);
pRstRoySched->UpdateBatch(adAffectCurrent);
}
else {
blnFound = FALSE;
printf("This Title ID not available");
}

// Show the results.


VARIANT varFilter;
varFilter.vt = VT_I2;
varFilter.iVal = adFilterNone;
pRstRoySched->PutFilter (varFilter);
pRstRoySched->Requery(-1);

// Bind the Recordset to a C++ Class here.


TESTHR(picRs->BindToRecordset(&royschrs));

printf("\nAfter delete there are %d titles with 20 percent royalty: ",


pRstRoySched->RecordCount);

while ( !(pRstRoySched->EndOfFile) ) {
printf("\n%s", royschrs.lemp_titleidStatus == adFldOK ?
royschrs.m_sz_titleid : "<NULL>");
pRstRoySched->MoveNext();
}

// Restore the data because this is a demonstration.


if ( blnFound ) {
// Set the final character of the destination string to NULL.
royschrs.m_sz_titleid[sizeof(royschrs.m_sz_titleid) - 1] = '\0';
// The source string will get truncated if its length is
// longer than the length of the destination string minus one.
strncpy_s(royschrs.m_sz_titleid, strTmpTitleID, sizeof(royschrs.m_sz_titleid) - 1);
royschrs.m_sz_lorange = intLoRange;
royschrs.m_sz_hirange = longHiRange;
royschrs.m_sz_royalty = intRoyalty;

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();

// 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;
}
}

// Clean up objects before exit. Release the IADORecordset Interface here


if (picRs)
picRs->Release();

if (pRstRoySched)
if (pRstRoySched->State == adStateOpen)
pRstRoySched->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

Sample Input
TC4203

Sample Output
Before delete there are 7 titles with 20 percent royalty :
BU2075
MC3021
TC3218
BU1111
MC2222
TC4203
BU7832

Enter the ID of a record to delete:


After delete there are 6 titles with 20 percent royalty:
BU2075
MC3021
TC3218
BU1111
MC2222
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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

Dim Cnxn As ADODB.Connection


Dim rstTitles As ADODB.Recordset
Dim rstPublishers As ADODB.Recordset
Dim rstPublishersDirect As ADODB.Recordset
Dim rstTitlesPublishers As ADODB.Recordset
Dim cmdSQL As ADODB.Command
Dim strCnxn As String
Dim strSQL As String

' Open a connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open a recordset based on a command object


Set cmdSQL = New ADODB.Command
Set cmdSQL.ActiveConnection = Cnxn
strSQL = "Select title, type, pubdate FROM Titles ORDER BY title"
cmdSQL.CommandText = strSQL
Set rstTitles = cmdSQL.Execute()

' Open a recordset based on a table


Set rstPublishers = New ADODB.Recordset
strSQL = "Publishers"
rstPublishers.Open strSQL, Cnxn, adOpenStatic, adLockReadOnly, adCmdTable
'rstPublishers.Open strSQL, Cnxn, , , adCmdTable
' the above two lines of code are identical

' Open a recordset based on a table


Set rstPublishersDirect = New ADODB.Recordset
rstPublishersDirect.Open strSQL, strCnxn, , , adCmdTableDirect

' Open a recordset based on an SQL string.


Set rstTitlesPublishers = New ADODB.Recordset
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"
rstTitlesPublishers.Open strSQL, strCnxn, , , adCmdText

' 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

If Not rstPublishers Is Nothing Then


If rstPublishers.State = adStateOpen Then rstPublishers.Close
End If
Set rstPublishers = Nothing

If Not rstTitlesPublishers Is Nothing Then


If rstTitlesPublishers.State = adStateOpen Then rstTitlesPublishers.Close
End If
Set rstTitlesPublishers = Nothing

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndSourceVB

See Also
Recordset Object (ADO )
Source Property (ADO Recordset)
Fields Collection (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Contains all the Field objects of a Recordset or Record object.

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"

// class extracts only store name from "stores" table.


class CStores : public CADORecordBinding {
BEGIN_ADO_BINDING(CStores)

// Column stor_name is the 1st field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, m_szS_stor_name, sizeof(m_szS_stor_name),
lS_stor_nameStatus, FALSE)

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

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 {
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];

// Define Other Variables


HRESULT hr = S_OK;
int intLoop = 0;
_bstr_t strSQL;
_bstr_t strMessage;
_bstr_t strFind;
int intLoop1 = 0;
char *tempStr;
bool boolFlag = TRUE;
char m_szS_stor_name[150];
char * token1;

// Assign SQL statement and connection string to variables.


strSQL = "SELECT stor_name FROM Stores ORDER BY stor_name";

_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated


Security='SSPI';");

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

// Create two clones of the original Recordset.


arstStores[1] = arstStores[0]->Clone(adLockUnspecified);
arstStores[2] = arstStores[0]->Clone(adLockUnspecified);

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");

_bstr_t str1 = arstStores[0]->Fields->GetItem("stor_name")->Value;


printf("\t1 - Original - Record pointer at %s", (LPCSTR)str1);

_bstr_t str2 = arstStores[1]->Fields->GetItem("stor_name")->Value;


printf("\n\t2 - Clone - Record pointer at %s", (LPCSTR)str2);

_bstr_t str3 = arstStores[2]->Fields->GetItem("stor_name")->Value;


printf("\n\t3 - Clone - Record pointer at %s", (LPCSTR)str3);

printf("\n\nEnter search string for # %d, or press Enter to quit.\n", intLoop);


mygets(m_szS_stor_name, 150);

// Trim the String.


tempStr = strtok_s(m_szS_stor_name, " \t", &token1);
strMessage = tempStr;
if (tempStr == NULL) {
boolFlag = FALSE;
break;
}

// Find the search string; if there's no


// match, jump to the last record.
intLoop1 = intLoop - 1;

arstStores[intLoop1]->Filter = "stor_name >= '" +


arstStores[intLoop1]->Filter = "stor_name >= '" +
strMessage + "'";

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;
}
}

// Clean up objects before exit.


if (arstStores[0])
if (arstStores[0]->State == adStateOpen)
arstStores[0]->Close();
if (arstStores[1])
if (arstStores[1]->State == adStateOpen)
arstStores[1]->Close();
if (arstStores[2])
if (arstStores[2]->State == adStateOpen)
arstStores[2]->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
};

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}
See Also
Recordset Object (ADO )
WriteText Method
10/1/2018 • 2 minutes to read • Edit Online

Writes a specified text string to a Stream object.

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

Indicates the ordinal position of a Recordset object's current record.

Settings and Return Values


For 32-bit code, sets or returns a Long value from 1 to the number of records in the Recordset object
(RecordCount), or returns one of the PositionEnum values.
For 64-bit code, use a data type that provides for storage of a 64-bit value. For example, you might use either
Long or another value that is 64-bit length such as DBORDINAL. Do not use PositionEnum values since they
are limited to 32-bit length.

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

Indicates the type of Record object.

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.

<!-- BeginDeleteVBS -->


<%@ Language=VBScript %>
<% ' use this meta tag instead of ADOVBS.inc%>
<!-- METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->
<HTML>
<HEAD>
<TITLE>ADO Delete Method</TITLE>
</HEAD>
<STYLE>
<!--
TH {
background-color: #008080;
font-family: 'Arial Narrow','Arial',sans-serif;
font-size: xx-small;
color: white;
}
TD {
text-align: center;
background-color: #f7efde;
font-family: 'Arial Narrow','Arial',sans-serif;
font-size: xx-small;
}
-->
</STYLE>

<BODY>
<H3>ADO Delete Method</H3>

<%
' to integrate this code replace the DataSource value in the connection string

' connection and recordset variables


Dim Cnxn, strCnxn
Dim rsCustomers, strSQLCustomers

' create and open connection


Set Cnxn = Server.CreateObject("ADODB.Connection")
strCnxn="Provider='sqloledb';Data Source=" & _
Request.ServerVariables("SERVER_NAME") & ";" & _
"Integrated Security='SSPI';Initial Catalog='Northwind';"
Cnxn.Open strCnxn
' create and open recordset
Set rsCustomers = Server.CreateObject("ADODB.Recordset")
strSQLCustomers = "Customers"
rsCustomers.Open strSQLCustomers, Cnxn, adOpenKeyset, adLockOptimistic, adCmdTable

' Move to designated record and delete it


If Not IsEmpty(Request.Form("WhichRecord")) Then
'Get value to move from Form Post method
Moves = Request.Form("WhichRecord")

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
%>

<!-- BEGIN column header row for Customer Table-->


<TABLE COLSPAN=8 CELLPADDING=5 BORDER=0>
<TR>
<TH>Rec. #</TH>
<TH>Company Name</TH>
<TH>Contact Name</TH>
<TH>City</TH>
</TR>

<%
' 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>

<Form Method=Post Action="Deletevbs.asp" Name=Form>


<Input Type=Text Name="WhichRecord" Size=3>
<Input Type=Button Name=cmdDelete Value="Delete Record">
</Form>

</BODY>

<Script Language = "VBScript">


Sub cmdDelete_OnClick
If IsNumeric(Document.Form.WhichRecord.Value) Then
Document.Form.WhichRecord.Value = CInt(Document.Form.WhichRecord.Value)
Dim Response
Response = MsgBox("Are You Sure About Deleting This Record?", vbYesNo, "ADO-ASP Example")

If Response = vbYes Then


Document.Form.Submit
End If
Else
MsgBox "You Must Enter a Valid Record Number",,"ADO-ASP Example"
End If
End Sub
</Script>

<%
' 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

'Instantiate and open stream


Set objStream = New Stream
objStream.Open

'Set line separator to line feed


objStream.LineSeparator = adLF

'Load text content of list box into stream


'One line at a time
For i = 0 To (List1.ListCount - 1)
objStream.WriteText List1.List(i), adWriteLine
Next

'Display the entire stream


Debug.Print "Whole Stream:"
objStream.Position = 0
Debug.Print objStream.ReadText

'Display the first line


Debug.Print "First Line:"
objStream.Position = 0
strLine = objStream.ReadText(adReadLine)
Debug.Print strLine
Debug.Print "Line length: " + Str(Len(strLine))

'Skip a line, then display another line


Debug.Print "Third Line:"
objStream.SkipLine
strLine = objStream.ReadText(adReadLine)
Debug.Print strLine
Debug.Print "Line length: " + Str(Len(strLine))

'Switch line separator to carriage return


'All items from list will be considered one line
'Assuming no CRs have been loaded into stream
Debug.Print "Whole Stream/First Line:"
objStream.Position = 0
objStream.LineSeparator = adCR
strLine = objStream.ReadText(adReadLine)
Debug.Print strLine
Debug.Print "Line length: " + Str(Len(strLine))
Debug.Print "Stream size: " + Str(objStream.Size)

'Use EOS to Determine End of Stream


'Use EOS to Determine End of Stream
Debug.Print "Character by character:"
objStream.Position = 0
Do Until objStream.EOS
strChar = objStream.ReadText(1)
Debug.Print strChar
Loop

' 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

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub

Private Sub Form_Load()


List1.AddItem "This is the first line"
List1.AddItem "This is the second line"
List1.AddItem "This is the third line"
End Sub
'EndSkipLineVB

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

Fields Collection (ADO) Recordset Object (ADO)

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

Indicates the actual length of a field's value in bytes.

Settings and Return Values


Returns a Long value.

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

Dim Cnxn As ADODB.Connection


Dim strCnxn As String
Dim strVersionInfo As String

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

strVersionInfo = "ADO Version: " & Cnxn.Version & vbCr


strVersionInfo = strVersionInfo & "DBMS Name: " & Cnxn.Properties("DBMS Name") & vbCr
strVersionInfo = strVersionInfo & "DBMS Version: " & Cnxn.Properties("DBMS Version") & vbCr
strVersionInfo = strVersionInfo & "OLE DB Version: " & Cnxn.Properties("OLE DB Version") & vbCr
strVersionInfo = strVersionInfo & "Provider Name: " & Cnxn.Properties("Provider Name") & vbCr
strVersionInfo = strVersionInfo & "Provider Version: " & Cnxn.Properties("Provider Version") & vbCr

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

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndVersionVB

See Also
Connection Object (ADO )
Version Property (ADO )
SetEOS Method
10/1/2018 • 2 minutes to read • Edit Online

Sets the position that is the end of the stream.

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;

_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);

pRstSchema = pConnection->OpenSchema(adSchemaTables);

while ( !(pRstSchema->EndOfFile) ) {
_bstr_t table_name = pRstSchema->Fields->GetItem("TABLE_NAME")->Value;

printf("Table Name: %s\n",(LPCSTR) table_name);

_bstr_t table_type = pRstSchema->Fields->GetItem("TABLE_TYPE")->Value;

printf("Table type: %s\n\n",(LPCSTR) table_type);

pRstSchema->MoveNext();
}
}
catch (_com_error &e) {
// Display errors, if any. Pass connection pointer accessed from the Connection.
PrintProviderError(pConnection);
PrintComError(e);
}
}

// Clean up objects before exit.


if (pRstSchema)
if (pRstSchema->State == adStateOpen)
pRstSchema->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void OpenSchemaX2() {
// Define ADO object pointers. Initialize pointers on define.
// These are in the ADODB:: namespace.
_ConnectionPtr pConnection2 = NULL;
_RecordsetPtr pRstSchema = NULL;

_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated


Security='SSPI';");

try {
// Open connection.
TESTHR(pConnection2.CreateInstance(__uuidof(Connection)));
pConnection2->Open (strCnn, "", "", adConnectUnspecified);

// Create a safearray which takes four elements,and pass it as


// 2nd parameter in OpenSchema method.
SAFEARRAY FAR* psa = NULL;
SAFEARRAYBOUND rgsabound;
_variant_t var;
_variant_t Array;
rgsabound.lLbound = 0;
rgsabound.cElements = 4;
psa = SafeArrayCreate(VT_VARIANT, 1, &rgsabound);
var.vt = VT_EMPTY;

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

printf("Table type: %s\n\n",


(LPCSTR) (_bstr_t) pRstSchema->Fields->GetItem("TABLE_TYPE")->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);
}

// Clean up objects before exit.


if (pRstSchema)
if (pRstSchema->State == adStateOpen)
pRstSchema->Close();
if (pConnection2)
if (pConnection2->State == adStateOpen)
pConnection2->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print COM errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

See Also
OpenSchema Method
FieldAttributeEnum
11/28/2018 • 2 minutes to read • Edit Online

Specifies one or more attributes of a Field object.

CONSTANT VALUE DESCRIPTION

adFldCacheDeferred 0x1000 Indicates that the provider caches field


values and that subsequent reads are
done from the cache.

adFldFixed 0x10 Indicates that the field contains fixed-


length data.

adFldIsChapter 0x2000 Indicates that the field contains a


chapter value, which specifies a specific
child recordset related to this parent
field. Typically chapter fields are used
with data shaping or filters.

adFldIsCollection 0x40000 Indicates that the field specifies that the


resource represented by the record is a
collection of other resources, such as a
folder, rather than a simple resource,
such as a text file.

adFldKeyColumn 0x8000 Indicates that the field specifies all or


part of the column's primary key.

adFldIsDefaultStream 0x20000 Indicates that the field contains the


default stream for the resource
represented by the record. For example,
the default stream can be the HTML
content of a root folder on a Web site,
which is automatically served when the
root URL is specified.

adFldIsNullable 0x20 Indicates that the field accepts null


values.

adFldIsRowURL 0x10000 Indicates that the field contains the URL


that names the resource from the data
store represented by the record.

adFldLong 0x80 Indicates that the field is a long binary


field. Also indicates that you can use
the AppendChunk and GetChunk
methods.

adFldMayBeNull 0x40 Indicates that you can read null values


from the field.
CONSTANT VALUE DESCRIPTION

adFldMayDefer 0x2 Indicates that the field is deferred-that


is, the field values are not retrieved
from the data source with the whole
record, but only when you explicitly
access them.

adFldNegativeScale 0x4000 Indicates that the field represents a


numeric value from a column that
supports negative scale values. The
scale is specified by the NumericScale
property.

adFldRowID 0x100 Indicates that the field contains a


persistent row identifier that cannot be
written to and has no meaningful value
except to identify the row (such as a
record number, unique identifier, and so
forth).

adFldRowVersion 0x200 Indicates that the field contains some


kind of time or date stamp used to
track updates.

adFldUnknownUpdatable 0x8 Indicates that the provider cannot


determine if you can write to the field.

adFldUnspecified -1 0xFFFFFFFF Indicates that the provider does not


specify the field attributes.

adFldUpdatable 0x4 Indicates that you can write to the field.

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

Append Method (ADO) Attributes Property (ADO)


OriginalValue Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online

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;

// Assign connection string to a variable


_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");

try {
// Open a recordset from Titles table
TESTHR(pRstTitles.CreateInstance(__uuidof(Recordset)));

// Fill array with CursorType constants.


int aintCursorType[4];
aintCursorType[0] = adOpenForwardOnly;
aintCursorType[1] = adOpenKeyset;
aintCursorType[2] = adOpenDynamic;
aintCursorType[3] = adOpenStatic;

// Open recordset using each CursorType and optimistic locking.


// Then call the DisplaySupport procedure to display the supported options.
for (int intIndex=0 ; intIndex <= 3 ; intIndex++) {
pRstTitles->CursorType = (enum CursorTypeEnum)aintCursorType[intIndex];
pRstTitles->LockType = adLockOptimistic;

// Pass the Cursor type and LockType to the Recordset.


pRstTitles->Open ("titles", strCnn,
(enum CursorTypeEnum)aintCursorType[intIndex], adLockOptimistic, adCmdTable);

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();

// 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;
}
}

// Clean up objects before exit.


if (pRstTitles)
if (pRstTitles->State == adStateOpen)
pRstTitles->Close();
}

void DisplaySupport (_RecordsetPtr pRstTemp) {


// Fill array with cursor option constants.
long alngConstants[11];
alngConstants[0] = adAddNew;
alngConstants[1] = adApproxPosition;
alngConstants[2] = adBookmark;
alngConstants[3] = adDelete;
alngConstants[4] = adFind;
alngConstants[5] = adHoldRecords;
alngConstants[6] = adMovePrevious;
alngConstants[7] = adNotify;
alngConstants[8] = adResync;
alngConstants[9] = adUpdate;
alngConstants[10] = adUpdateBatch;

for ( int intIndex = 0 ; intIndex <= 10 ; intIndex++ ) {


VARIANT_BOOL booSupports = pRstTemp->Supports( (enum CursorOptionEnum)alngConstants[intIndex] );

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;
}
}
}
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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.

CONSTANT VALUE DESCRIPTION

adCreateCollection 0x2000 Creates a new Record at the node


specified by Source parameter, instead
of opening an existing Record. If the
source points to an existing node, then
a run-time error occurs, unless
adCreateCollection is combined with
adOpenIfExists or
adCreateOverwrite.

adCreateNonCollection 0 Creates a new Record of type


adSimpleRecord.

adCreateOverwrite 0x4000000 Modifies the creation flags


adCreateCollection,
adCreateNonCollection, and
adCreateStructDoc. When OR is used
with this value and one of the creation
flag values, if the source URL points to
an existing node or Record, then the
existing Record is overwritten and a
new one is created in its place. This
value cannot be used together with
adOpenIfExists.

adCreateStructDoc 0x80000000 Creates a new Record of type


adStructDoc, instead of opening an
existing Record.

adFailIfNotExists -1 Default. Results in a run-time error if


Source points to a non-existent node.

adOpenIfExists 0x2000000 Modifies the creation flags


adCreateCollection,
adCreateNonCollection, and
adCreateStructDoc. When OR is used
with this value and one of the creation
flag values, if the source URL points to
an existing node or Record object, then
the provider must open the existing
Record instead of creating a new one.
This value cannot be used together with
adCreateOverwrite.

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

Moves the entity represented by a Record to another location.

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;

enum ParameterDirectionEnum GetDirection( );


void PutDirection( enum ParameterDirectionEnum plParmDirection );
__declspec(property(get=GetDirection,put=PutDirection)) enum
ParameterDirectionEnum Direction;

_bstr_t GetName( );
void PutName( _bstr_t pbstr );
__declspec(property(get=GetName,put=PutName)) _bstr_t Name;

unsigned char GetNumericScale( );


void PutNumericScale( unsigned char pbScale );
__declspec(property(get=GetNumericScale,put=PutNumericScale)) unsigned
char NumericScale;

unsigned char GetPrecision( );


void PutPrecision( unsigned char pbPrecision );
__declspec(property(get=GetPrecision,put=PutPrecision)) unsigned char
Precision;

long GetSize( );
void PutSize( long pl );
__declspec(property(get=GetSize,put=PutSize)) long Size;

enum DataTypeEnum GetType( );


void PutType( enum DataTypeEnum psDataType );
__declspec(property(get=GetType,put=PutType)) enum DataTypeEnum Type;

_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

Fields Collection (ADO) Recordset Object (ADO)

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

For more information, see


Append Method (ADO )
Delete Method (ADO Parameters Collection)
Refresh Method (ADO )
Properties

get_Count(long *c);
get_Item(VARIANT Index, _ADOParameter **ppvObject);

For more information, see


Count Property (ADO )
Item Property (ADO )

Fields
Methods

Append(BSTR bstrName, DataTypeEnum Type, long DefinedSize, FieldAttributeEnum Attrib);


Delete(VARIANT Index);
Refresh(void);

For more information, see


Append Method (ADO )
Delete Method (ADO Parameters Collection)
Refresh Method (ADO )
Properties

get_Count(long *c);
get_Item(VARIANT Index, ADOField **ppvObject);

For more information, see


Count Property (ADO )
Item Property (ADO )

Errors
Methods

Clear(void);
Refresh(void);

For more information, see


Clear Method (ADO )
Refresh Method (ADO )
Properties

get_Count(long *c);
get_Item(VARIANT Index, ADOError **ppvObject);

For more information, see


Count Property (ADO )
Item Property (ADO )

Properties
Methods

Refresh(void);

For more information, see


Refresh Method (ADO )
Properties

get_Count(long *c);
get_Item(VARIANT Index, ADOProperty **ppvObject);

For more information, see


Count Property (ADO )
Item Property (ADO )

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

'Instantiate and Open Stream


Set objStream = New Stream
objStream.Open

'Write the text content of a textbox to the stream


If Text1.Text = "" Then
Err.Raise 1, , "The text field is blank."
End If
objStream.WriteText Text1.Text

'Display the text contents and size of the stream


objStream.Position = 0
Debug.Print "Default text:"
Debug.Print objStream.ReadText
Debug.Print objStream.Size

'Switch character set and display


objStream.Position = 0
objStream.Charset = "Windows-1252"
Debug.Print "New Charset text:"
Debug.Print objStream.ReadText
Debug.Print objStream.Size

'Switch to a binary stream and display


objStream.Position = 0
objStream.Type = adTypeBinary
Debug.Print "Binary:"
Debug.Print objStream.Read
Debug.Print objStream.Size

'Load an array of bytes with the text box text


ReDim bytA(Len(Text1.Text))
For i = 1 To Len(Text1.Text)
bytA(i - 1) = CByte(Asc(Mid(Text1.Text, i, 1)))
Next

'Write the buffer to the binary stream and display


objStream.Position = 0
objStream.Write bytA()
objStream.SetEOS
objStream.Position = 0
Debug.Print "Binary after Write:"
Debug.Print objStream.Read
Debug.Print objStream.Read
Debug.Print objStream.Size

'Switch back to a text stream and display


Debug.Print "Translated back:"
objStream.Position = 0
objStream.Type = adTypeText
Debug.Print objStream.ReadText
Debug.Print objStream.Size

' 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

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndReadVB

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

Specifies a name for the Recordset object.

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

Specifies how a provider should execute a command.

CONSTANT VALUE DESCRIPTION

adAsyncExecute 0x10 Indicates that the command should


execute asynchronously.

This value cannot be combined with the


CommandTypeEnum value
adCmdTableDirect.

adAsyncFetch 0x20 Indicates that the remaining rows after


the initial quantity specified in the
CacheSize property should be retrieved
asynchronously.

adAsyncFetchNonBlocking 0x40 Indicates that the main thread never


blocks while retrieving. If the requested
row has not been retrieved, the current
row automatically moves to the end of
the file.

If you open a Recordset from a Stream


containing a persistently stored
Recordset,
adAsyncFetchNonBlocking will not
have an effect; the operation will be
synchronous and blocking.

adAsynchFetchNonBlocking has no
effect when the adCmdTableDirect
option is used to open the Recordset.

adExecuteNoRecords 0x80 Indicates that the command text is a


command or stored procedure that
does not return rows (for example, a
command that only inserts data). If any
rows are retrieved, they are discarded
and not returned.

adExecuteNoRecords can only be


passed as an optional parameter to the
Command or Connection Execute
method.

adExecuteStream 0x400 Indicates that the results of a command


execution should be returned as a
stream.

adExecuteStream can only be passed


as an optional parameter to the
Command Execute method.
CONSTANT VALUE DESCRIPTION

adExecuteRecord Indicates that the CommandText is a


command or stored procedure that
returns a single row which should be
returned as a Record object.

adOptionUnspecified -1 Indicates that the command is


unspecified.

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

Execute Method (ADO Command) Execute Method (ADO Connection)

Open Method (ADO Recordset) Requery Method


Filter and RecordCount Properties Example (JScript)
10/1/2018 • 2 minutes to read • Edit Online

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.

<!-- BeginFilterJS -->


<%@ Language=JavaScript %>
<%// use this meta tag instead of adojavas.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->

<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">

<h1>ADO Recordset.Filter Example</h1>


<!-- Page text goes here -->
<%
// 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 rsCustomers = Server.CreateObject("ADODB.Recordset");
var SQLCustomers = "select * from Customers;";
// record variables
var fld, filter
var showBlank = " ";
var showNull = "-NULL-";

try
try
{
//open connection
Cnxn.Open(strCnxn);

// create recordset client-side using object refs


rsCustomers.ActiveConnection = Cnxn;
rsCustomers.CursorLocation = adUseClient;
rsCustomers.CursorType = adOpenKeyset;
rsCustomers.LockType = adLockOptimistic;
rsCustomers.Source = SQLCustomers;
rsCustomers.Open();

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection strings

Public Sub Main()


On Error GoTo ErrorHandler

Dim Cnxn1 As ADODB.Connection


Dim Cnxn2 As ADODB.Connection
Dim Cnxn3 As ADODB.Connection
Dim strCnxn As String

' Open a connection using the Microsoft ODBC provider


Set Cnxn1 = New ADODB.Connection
Cnxn1.ConnectionString = "driver={SQL Server};server='MySqlServer';" & _
"user id='MyUserID';password='MyPassword';"
Cnxn1.Open strCnxn
Cnxn1.DefaultDatabase = "Pubs"

' Display the provider


MsgBox "Cnxn1 provider: " & Cnxn1.Provider

' Open a connection using the Microsoft Jet provider


Set Cnxn2 = New ADODB.Connection
Cnxn2.Provider = "Microsoft.Jet.OLEDB.4.0"
Cnxn2.Open "Northwind.mdb", _
"MyUserID", "MyPassword"

' Display the provider.


MsgBox "Cnxn2 provider: " & Cnxn2.Provider

' Open a connection using the Microsoft SQL Server provider


Set Cnxn3 = New ADODB.Connection
Cnxn3.Provider = "sqloledb"
Cnxn3.Open "Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"

' Display the provider


MsgBox "Cnxn3 provider: " & Cnxn3.Provider

' 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

If Not Cnxn2 Is Nothing Then


If Cnxn2.State = adStateOpen Then Cnxn2.Close
End If
Set Cnxn2 = Nothing

If Not Cnxn3 Is Nothing Then


If Cnxn3.State = adStateOpen Then Cnxn3.Close
End If
Set Cnxn3 = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If

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.

<!-- BeginOpenVBS -->


<%@ Language=VBScript %>
<%' use this meta tag instead of adovbs.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->
<HTML>
<HEAD>
<META name="VI60_DefaultClientScript" content=VBScript>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<title>ADO Open Method</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>
<H3>ADO Open Method</H3>

<TABLE WIDTH=600 BORDER=0>


<TR>
<TD VALIGN=TOP COLSPAN=3>
<FONT SIZE=2>
<% ' to integrate/test this code replace the
' Data Source value in the Connection string%>
<%
' connection and recordset variables
Dim Cnxn, strCnxn
Dim rsCustomers, strSQLCustomers
Dim rsProducts, strSQLProducts
Dim rsProducts, strSQLProducts

' open connection


Set Cnxn = Server.CreateObject("ADODB.Connection")
strCnxn = "Provider='sqloledb';Data Source=" & _
Request.ServerVariables("SERVER_NAME") & ";" & _
"Integrated Security='SSPI';Initial Catalog='Northwind';"

Cnxn.Open strCnxn

' create and open first Recordset using Connection - execute


Set rsCustomers = Server.CreateObject("ADODB.Recordset")
strSQLCustomers = "SELECT CompanyName, ContactName, City FROM Customers"
Set rsCustomers = Cnxn.Execute(strSQLCustomers)

' create and open second Recordset using recordset - open


Set rsProducts = Server.CreateObject("ADODB.Recordset")
strSQLProducts = "SELECT ProductName, UnitPrice FROM Products"
rsProducts.Open strSQLProducts, Cnxn, adOpenDynamic, adLockPessimistic, adCmdText
%>

<TABLE COLSPAN=8 CELLPADDING=5 BORDER=0>


<!-- BEGIN column header row for Customer Table-->
<TR CLASS=thead>
<TD>Company Name</TD>
<TD>Contact Name</TD>
<TD>City</TD>
</TR>

<!--Display ADO Data from Customer Table-->


<% Do Until rsCustomers.EOF %>
<TR CLASS=tbody>
<TD> <%=rsCustomers("CompanyName")%> </TD>
<TD> <%=rsCustomers("ContactName")%></TD>
<TD> <%=rsCustomers("City")%> </TD>
</TR>
<%rsCustomers.MoveNext
Loop
%>
</TABLE>

<HR>

<TABLE COLSPAN=8 CELLPADDING=5 BORDER=0>


<!-- BEGIN column header row for Product List Table-->

<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

Opens a connection to a data source.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string.

' Declare the recordset and connection variables.


Dim Cnxn As ADODB.Connection
Dim rstAuthors As ADODB.Recordset
Dim strCnxn As String
Dim strSQLAuthors As String

' Open connection.


strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Set Cnxn = New ADODB.Connection
Cnxn.Open strCnxn

' open recordset client-side to enable index creation.


Set rstAuthors = New ADODB.Recordset
rstAuthors.CursorLocation = adUseClient
strSQLAuthors = "SELECT * FROM Authors"
rstAuthors.Open strSQLAuthors, Cnxn, adOpenStatic, adLockReadOnly, adCmdText
' Create the index.
rstAuthors!zip.Properties("Optimize") = True
' Find Akiko Yokomoto
rstAuthors.Find "zip = '94595'"

' Show results.


Debug.Print rstAuthors!au_fname & " " & rstAuthors!au_lname & " " & _
rstAuthors!address & " " & rstAuthors!city & " " & rstAuthors!State
rstAuthors!zip.Properties("Optimize") = False 'Delete the index.

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndOptimizeVB

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" .

This property may be a null value if:


There is no parent for the current object; for example, if the Record object represents the root of a
directory.
The Record object represents an entity that cannot be specified with a URL.
This property is read-only.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

'recordset array and connection variables


Dim arstStores(1 To 3) As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strSQLStore As String
Dim strCnxn As String
'record variables
Dim intLoop As Integer
Dim strMessage As String
Dim strFind As String

' Open a connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open recordset as a static cursor type recordset


Set arstStores(1) = New ADODB.Recordset
strSQLStore = "SELECT stor_name FROM Stores ORDER BY stor_name"
arstStores(1).Open strSQLStore, strCnxn, adOpenStatic, adLockBatchOptimistic, adCmdText

' Create two clones of the original Recordset


Set arstStores(2) = arstStores(1).Clone
Set arstStores(3) = arstStores(1).Clone

' 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

' otherwise locate the record from the entered string


arstStores(intLoop).Filter = "stor_name = '" & strFind & "'"

'if there's no match, jump to the last record


If arstStores(intLoop).EOF Then
If arstStores(intLoop).EOF Then
arstStores(intLoop).Filter = adFilterNone
arstStores(intLoop).MoveLast
Else
MsgBox "Found " & strFind
End If
Next intLoop
Loop

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndCloneVB

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

Dim rstTitles As ADODB.Recordset


Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQLTitles As String

' Open a connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open recordset containing the 10 most expensive


' titles in the Titles table
Set rstTitles = New ADODB.Recordset
rstTitles.MaxRecords = 10

strSQLTitles = "SELECT Title, Price FROM Titles ORDER BY Price DESC"


rstTitles.Open strSQLTitles, strCnxn, adOpenStatic, adLockReadOnly, adCmdText

' Display the contents of the recordset


Debug.Print "Top Ten Titles by Price:"

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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndMaxRecordsVB

See Also
MaxRecords Property (ADO )
Recordset Object (ADO )
ExecuteComplete Event (ADO)
10/1/2018 • 2 minutes to read • Edit Online

The ExecuteComplete event is called after a command has finished executing.

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

Private Sub Form_Load()


On Error GoTo ErrorHandler

' Declare variables


Dim strPicturePath, strStreamPath, strStream2Path, _
strRecordPath, strStreamURL, strRecordURL As String
Dim objStream, objStream2 As Stream
Dim objRecord As Record
Dim objField As Field

' Instantiate objects


Set objStream = New Stream
Set objStream2 = New Stream
Set objRecord = New Record

' Initialize path and URL strings


strPicturePath = "C:\checkmrk.wmf"
strStreamPath = "C:\mywmf.wmf"
strStreamURL = "URL=https://MyServer/mywmf.wmf"
strStream2Path = "C:\checkmrk2.wmf"
strRecordPath = "C:\mywmf.wmf"
strRecordURL = "https://MyServer/mywmf2.wmf"

' Load the file into the stream


objStream.Open
objStream.Type = adTypeBinary
objStream.LoadFromFile (strPicturePath)

' Save the stream to a new path and filename


objStream.SaveToFile strStreamPath, adSaveCreateOverWrite

' Copy the contents of the first stream to a second stream


objStream2.Open
objStream2.Type = adTypeBinary
objStream.CopyTo objStream2

' Save the second stream to a different path


objStream2.SaveToFile strStream2Path, adSaveCreateOverWrite

' Because strStreamPath is a Web Folder, open a Record on the URL


objRecord.Open "", strStreamURL

' Display the Fields of the record


For Each objField In objRecord.Fields
Debug.Print objField.Name & ": " & objField.Value
Debug.Print objField.Name & ": " & objField.Value
Next

' Copy the record to a new URL


objRecord.CopyRecord "", strRecordURL, , , adCopyOverWrite

' 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

If Not objStream2 Is Nothing Then


If objStream2.State = adStateOpen Then objStream2.Close
End If
Set objStream2 = Nothing

If Not objRecord Is Nothing Then


If objRecord.State = adStateOpen Then objRecord.Close
End If
Set objRecord = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndCopyRecordVB

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

Dim Cnxn As ADODB.Connection


Dim Err As ADODB.Error
Dim strError As String

On Error GoTo ErrorHandler

' Intentionally trigger an error


Set Cnxn = New ADODB.Connection
Cnxn.Open "nothing"

Set Cnxn = Nothing


Exit Sub

ErrorHandler:

' Enumerate Errors collection and display


' properties of each Error object
For Each Err In Cnxn.Errors
strError = "Error #" & Err.Number & vbCr & _
" " & Err.Description & vbCr & _
" (Source: " & Err.Source & ")" & vbCr & _
" (SQL State: " & Err.SQLState & ")" & vbCr & _
" (NativeError: " & Err.NativeError & ")" & vbCr
If Err.HelpFile = "" Then
strError = strError & " No Help file available"
Else
strError = strError & _
" (HelpFile: " & Err.HelpFile & ")" & vbCr & _
" (HelpContext: " & Err.HelpContext & ")" & _
vbCr & vbCr
End If

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

'recordset and connection variables


Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strCmdChange As String
Dim strCmdRestore As String
'record variables
Dim blnChanged As Boolean

' Open a connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Define command strings


strCmdChange = "UPDATE titles SET type = 'self_help' WHERE type = 'psychology'"
strCmdRestore = "UPDATE titles SET type = 'psychology' " & _
"WHERE type = 'self_help'"

' Begin a transaction, then execute a command asynchronously


Cnxn.BeginTrans
Cnxn.Execute strCmdChange, , adAsyncExecute
' do something else for a little while -
' use i = 1 to 32000 to allow completion
Dim i As Integer
For i = 1 To 1000
i = i + i
Debug.Print i
Next i

' 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

' If the change was made, restore the data


' because this is only a demo
If blnChanged Then
Cnxn.Execute strCmdRestore
Cnxn.Execute strCmdRestore
MsgBox "Data restored."
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

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndCancelVB

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

'recordset and connection variables


Dim rstEmployees As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQL As String
'record variables
Dim strMessage As String
Dim intPage As Integer
Dim intPageCount As Integer
Dim intRecord As Integer

'Open connection
Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open employee recordset


' Use client cursor to enable AbsolutePosition property
Set rstEmployees = New ADODB.Recordset
strSQL = "employee"
rstEmployees.Open strSQL, strCnxn, adUseClient, adLockReadOnly, adCmdTable

' Display names and hire dates, five records at a time


rstEmployees.PageSize = 5
intPageCount = rstEmployees.PageCount
For intPage = 1 To intPageCount
rstEmployees.AbsolutePage = intPage
strMessage = ""
For intRecord = 1 To rstEmployees.PageSize
strMessage = strMessage & _
rstEmployees!fname & " " & _
rstEmployees!lname & " " & _
rstEmployees!hire_date & vbCr
rstEmployees.MoveNext
If rstEmployees.EOF Then Exit For
Next intRecord
MsgBox strMessage
Next intPage

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndAbsolutePageVB

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"

// This Class extracts only titleId from Titles table.


class CTitlesRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CTitlesRs)

// 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

_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);

// Open title Table


TESTHR(pRstTitles.CreateInstance(__uuidof(Recordset)));

pRstTitles->Open("SELECT title_id FROM titles",


pRstTitles->Open("SELECT title_id FROM titles",
_variant_t((IDispatch *)pConnection),
adOpenStatic, adLockReadOnly, adCmdText);

// The default parameters are sufficient to search forward through a Recordset.

pRstTitles->Find ("title_id LIKE 'BU%'", 0, adSearchForward, "");

// Open an IADORecordBinding interface pointer for Binding Recordset to a class


TESTHR(pRstTitles->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Bind the Recordset to a C++ Class here


TESTHR(picRs->BindToRecordset(&titlers));

// 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;

// Continue if last find succeeded.


while (!(pRstTitles->EndOfFile)) {
printf("Title ID: %s\n", titlers.lt_titleidStatus == adFldOK ?
titlers.m_szt_titleid : "<NULL>");
count++; // Count the last title found.

_variant_t mark = pRstTitles->Bookmark; // Note current pos.


pRstTitles->Find("title_id LIKE 'BU%'", 1, adSearchForward, mark);
}
printf("The number of business titles is %d\n", count);
}
catch(_com_error &e) {
// Display errors, if any. Pass connection pointer accessed from the Recordset.
PrintProviderError(pConnection);
PrintComError(e);
}

// Clean up objects before exit. Release the IADORecordset Interface here


if (picRs)
picRs->Release();

if (pRstTitles)
if (pRstTitles->State == adStateOpen)
pRstTitles->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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..

CONSTANT VALUE DESCRIPTION

adSaveCreateNotExist 1 Default. Creates a new file if the file


specified by the FileName parameter
does not already exist.

adSaveCreateOverWrite 2 Overwrites the file with the data from


the currently open Stream object, if the
file specified by the Filename parameter
already exists. If the file specified by the
Filename parameter does not exist, a
new file is created.

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;

// Define string variables.


_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");

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

SortXprint(" Initial Order ", pRstAuthors);

pRstAuthors->Sort = "au_lname ASC, au_fname ASC";


SortXprint("Last Name Ascending", pRstAuthors);

pRstAuthors->Sort = "au_lname DESC, au_fname ASC";


SortXprint("Last Name Descending", pRstAuthors);
}
catch(_com_error &e) {
PrintProviderError(pConnection);
PrintComError(e);
}

// Clean up objects before exit.


if (pRstAuthors)
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

// This is the secondary utility routine that prints


// the given title, and the contents of the specified Recordset.
void SortXprint(_bstr_t title, _RecordsetPtr rstp) {
printf("---------------%s---------------\n", (LPCSTR)title);
printf("First Name Last Name\n"
"---------------------------------------------------\n");
rstp->MoveFirst();
while (!(rstp->EndOfFile)) {
_bstr_t aufname;
_bstr_t aulname;
aufname = rstp->GetFields()->GetItem("au_fname")->Value;
aulname = rstp->GetFields()->GetItem("au_lname")->Value,
printf("%s %s\n",(LPCSTR) aufname, (LPCSTR) aulname);
rstp->MoveNext();
}
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

See Also
Recordset Object (ADO )
Sort Property
EOS Property
10/1/2018 • 2 minutes to read • Edit Online

Indicates whether the current position is at the end of the stream.

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"

// Class extracts only EmployeeId,FirstName and LastName from employees table


class CEmployeeRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CEmployeeRs)

// Column hiredate is the 1st field in the table.


ADO_VARIABLE_LENGTH_ENTRY2(1, adInteger,m_ie_empid, sizeof(m_ie_empid),
le_empidStatus, FALSE)

// Column LastName is the 2nd field in the table.


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_sze_lname, sizeof(m_sze_lname),
le_lnameStatus, FALSE)

// Column FirstName is the 3rd field in the table.


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_sze_fname, sizeof(m_sze_fname),
le_fnameStatus, FALSE)
END_ADO_BINDING()

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

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 {
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;

IADORecordBinding *picRs = NULL; // Interface Pointer declared


CEmployeeRs EmpRs; // C++ class object

// Definitions of other variables


_bstr_t strPrompt("Enter an EmployeeID (e.g., 1 to 9)");
char strEmpId[2];

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

// Open an IADORecordBinding interface pointer which


// we'll use for binding Recordset to a Class
TESTHR(pRstEmp->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Bind the Recordset to a C++ Class


TESTHR(picRs->BindToRecordset(&EmpRs));

// Does this provider support Seek and Index?


if (pRstEmp->Supports(adIndex) && pRstEmp->Supports(adSeek)) {
pRstEmp->Index = "PrimaryKey";

// Display all the employees.


pRstEmp->MoveFirst();
while (!pRstEmp->EndOfFile) {
printf("%d : %s %s\n",
EmpRs.le_empidStatus == adFldOK ?
EmpRs.m_ie_empid : 0,
EmpRs.le_fnameStatus == adFldOK ?
EmpRs.m_sze_fname : "<NULL>",
EmpRs.le_lnameStatus == adFldOK ?
EmpRs.m_sze_lname : "<NULL>");

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

// Quit if strEmpID is a zero-length string (CANCEL, null, etc.)


char *strTemp = strtok_s(strEmpId," \t", NULL);
if (strTemp == NULL) break;
if (strlen(strTemp) == 1 && atoi(strTemp) >= 1 && atoi(strTemp) <= 9) {
_variant_t strEmployeeId(strTemp);
_variant_t strEmployeeId(strTemp);
pRstEmp->Seek(strEmployeeId, adSeekAfterEQ);
if (pRstEmp->EndOfFile)
printf("Employee not found.\n");
else {
printf("%d : Employee='%s %s'\n",
EmpRs.le_empidStatus == adFldOK ?
EmpRs.m_ie_empid : 0,
EmpRs.le_fnameStatus == adFldOK ?
EmpRs.m_sze_fname : "<NULL>",
EmpRs.le_lnameStatus == adFldOK ?
EmpRs.m_sze_lname : "<NULL>");
}
}
} while(true);
}
}
catch(_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstEmp->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;
}
}

// Clean up objects before exit. Release the IADORecordset Interface here


if (picRs)
picRs->Release();

if (pRstEmp)
if (pRstEmp->State == adStateOpen)
pRstEmp->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print COM errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

' connection and recordset variables


Dim rstAuthors As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQLAuthors As String
' record variables
Dim varBookmark As Variant
Dim strCommand As String
Dim lngMove As Long

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open recordset from Authors table


Set rstAuthors = New ADODB.Recordset
rstAuthors.CursorLocation = adUseClient
' Use client cursor to allow use of AbsolutePosition property
strSQLAuthors = "SELECT au_id, au_fname, au_lname, city, state FROM Authors ORDER BY au_lname"
rstAuthors.Open strSQLAuthors, strCnxn, adOpenStatic, adLockOptimistic, adCmdText

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).")

' this is for exiting the loop


'lngMove = CLng(strCommand)

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

' Store bookmark in case the Move goes too far


' Store bookmark in case the Move goes too far
' forward or backward
varBookmark = rstAuthors.Bookmark

' Move method requires parameter of data type Long


rstAuthors.Move lngMove

' Trap for BOF or EOF


If rstAuthors.BOF Then
MsgBox "Too far backward! Returning to current record."
rstAuthors.Bookmark = varBookmark
End If
If rstAuthors.EOF Then
MsgBox "Too far forward! Returning to current record."
rstAuthors.Bookmark = varBookmark
End If
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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndMoveVB

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;

// Define Other Variables


_variant_t Index;
Index.vt = VT_I2;

_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated


Security='SSPI';");

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();

for (short int intLoop = 0 ; intLoop < (int)fldTemp->GetCount() ; intLoop++ ) {


Index.iVal = intLoop;

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();

// 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;
}
}

// Clean up objects before exit.


if (pRstDiscounts)
if (pRstDiscounts->State == adStateOpen)
pRstDiscounts->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print COM errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

See Also
NumericScale Property (ADO )
Precision Property (ADO )
BookmarkEnum
10/1/2018 • 2 minutes to read • Edit Online

Specifies a bookmark indicating where the operation should begin.

CONSTANT VALUE DESCRIPTION

adBookmarkCurrent 0 Starts at the current record.

adBookmarkFirst 1 Starts at the first record.

adBookmarkLast 2 Starts at the last record.

ADO/WFC Equivalent
Package: com.ms.wfc.data

CONSTANT

AdoEnums.Bookmark.CURRENT

AdoEnums.Bookmark.FIRST

AdoEnums.Bookmark.LAST

Applies To

GetRows Method (ADO) Move Method (ADO)


Find Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

' recordset and connection variables


Dim rstEmployees As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQLEmployees As String
' buffer variables
Dim strOldFirst As String
Dim strOldLast As String
Dim strMessage As String

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open recordset to enable changes


Set rstEmployees = New ADODB.Recordset
strSQLEmployees = "SELECT fname, lname FROM Employee ORDER BY lname"
rstEmployees.Open strSQLEmployees, Cnxn, adOpenKeyset, adLockOptimistic, adCmdText

' Store original data


strOldFirst = rstEmployees!fname
strOldLast = rstEmployees!lname
' Change data in edit buffer
rstEmployees!fname = "Linda"
rstEmployees!lname = "Kobara"

' Show contents of buffer and get user input


strMessage = "Edit in progress:" & vbCr & _
" Original data = " & strOldFirst & " " & _
strOldLast & vbCr & " Data in buffer = " & _
rstEmployees!fname & " " & rstEmployees!lname & vbCr & vbCr & _
"Use Update to replace the original data with " & _
"the buffered data in the Recordset?"

If MsgBox(strMessage, vbYesNo) = vbYes Then


rstEmployees.Update
Else
rstEmployees.CancelUpdate
End If

' show the resulting data


MsgBox "Data in recordset = " & rstEmployees!fname & " " & _
rstEmployees!lname

' restore original data because this is a demonstration


If Not (strOldFirst = rstEmployees!fname And _
strOldLast = rstEmployees!lname) Then
rstEmployees!fname = strOldFirst
rstEmployees!fname = strOldFirst
rstEmployees!lname = strOldLast
rstEmployees.Update
End If

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
' EndUpdateVB

This example demonstrates the Update method in conjunction with the AddNew method.

Attribute VB_Name = "Update"

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;

// Define Other Variables


_variant_t Index;
Index.vt = VT_I2;
int j = 0;

_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated


Security='SSPI';");

try {
// Open recordset with data from Employee table.
TESTHR(pRstEmployee.CreateInstance(__uuidof(Recordset)));
pRstEmployee->Open("Employee", strCnn, adOpenForwardOnly, adLockReadOnly, adCmdTable);

// Print information about Fields collection.


printf("%d Fields in Employee\n", pRstEmployee->Fields->Count);
for (short int intLoop = 0 ; intLoop <= (pRstEmployee->Fields->Count-1) ; intLoop++) {
Index.iVal = intLoop;
printf(" %s\n", (LPSTR) pRstEmployee->Fields->GetItem(Index)->Name);
}

// Print information about Properties collection.


printf("\n%d Properties in Employee\n", pRstEmployee->Properties->Count);
for (short int intLoop = 0 ; intLoop <= (pRstEmployee->Properties->Count - 1) ; intLoop++) {
j++;
Index.iVal = intLoop;
printf(" %s\n" , (LPSTR)pRstEmployee->Properties->GetItem(Index)->Name);
}
}
catch(_com_error &e) {
catch(_com_error &e) {
// Display any errors that result from executing the query.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstEmployee->GetActiveConnection();

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();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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;

// Define Other Variables


HRESULT hr = S_OK;

try {
// Intentionally trigger an error. open connection
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));

if (FAILED(hr = pConnection->Open("Nothing", "", "", adConnectUnspecified))) {


_com_issue_error(hr);
exit(1);
}

// Cleanup object before exit.


pConnection->Close();
}
catch(_com_error) {
// Pass a connection pointer.
PrintProviderError(pConnection);
}
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Define Other Variables
HRESULT hr = S_OK;
_bstr_t strError;
ErrorPtr pErr = NULL;

try {
// Enumerate Errors collection and display properties of each Error object.
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 #%d\n", pErr->Number);
printf(" %s\n", (LPCSTR)pErr->Description);
printf(" (Source: %s)\n", (LPCSTR)pErr->Source);
printf(" (SQL State: %s)\n", (LPCSTR)pErr->SQLState);
printf(" (NativeError: %d)\n", (LPCSTR)pErr->NativeError);

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);
}
}

void PrintComError(_com_error &e) {


// Notify the user of errors if any.
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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.

Settings and Return Values


Sets or returns a String value that contains a definition for a connection if the connection is closed, or a
Variant containing the current Connection object if the connection is open. Default is a null object reference.
See the ConnectionString property.

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

Command Object (ADO) Record Object (ADO) Recordset 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)
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));

2. Query the IADORecordConstruction interface on the Record object:

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

#define ChunkSize 100

#include <ole2.h>
#include <stdio.h>
#include "conio.h"
#include "malloc.h"
#include "icrsint.h"

// extracts pubid, prinfo.


class CPubInfoRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CPubInfoRs)
ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, m_sz_pubid, sizeof(m_sz_pubid), l_pubid, TRUE)
ADO_VARIABLE_LENGTH_ENTRY2(3, adVarChar, m_sz_prinfo, sizeof(m_sz_prinfo), l_prinfo, TRUE)
END_ADO_BINDING()

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

inline int myscanf(char* strDest, int n) {


char strExBuff[10];
char* pstrRet = fgets(strDest, n, stdin);

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;

// Define other variables


IADORecordBinding *picRs = NULL; // Interface Pointer declared.(VC++ Extensions)
CPubInfoRs pubrs; // C++ class object

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

// Open an IADORecordBinding interface pointer for Binding Recordset to a class


TESTHR(pRstPubInfo->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Bind the Recordset to a C++ Class here


TESTHR(picRs->BindToRecordset(&pubrs));
// Display the available logos here
strMessage = "Available logos are: " + (_bstr_t)"\n\n";
printf(strMessage);
int Counter = 0;
while (!(pRstPubInfo->EndOfFile)) {
printf("\n%s", pubrs.m_sz_pubid);
printf("\n%s", strtok_s(pubrs.m_sz_prinfo, ",", &token1));

// Display 5 records at a time and wait for user to continue..


if (++Counter >= 5) {
Counter = 0;
printf("\nPress any key to continue...");
_getch();
}
pRstPubInfo->MoveNext();
}

// Prompt For a Logo to Copy


printf("\nEnter the ID of a logo to copy: ");
myscanf(pubId, sizeof(pubId));
strPubID = pubId;

// Copy the logo to a variable in chunks


pRstPubInfo->Filter = "pub_id = '" + strPubID + "'";
lngLogoSize = pRstPubInfo->Fields->Item["logo"]->ActualSize;

// Create a safe array to store the array of BYTES


rgsabound[0].cElements = lngLogoSize;
psa = SafeArrayCreate(VT_UI1, 1, rgsabound);

long index1 = 0;
while (lngOffSet < lngLogoSize) {
varChunk = pRstPubInfo->Fields->Item["logo"]->GetChunk(ChunkSize);

// Copy the data only upto the Actual Size of Field.


for (long index = 0 ; index <= (ChunkSize - 1) ; index++) {
hr = SafeArrayGetElement(varChunk.parray, &index, &chData);
if (SUCCEEDED(hr)) {
// Take BYTE by BYTE and advance Memory Location
hr = SafeArrayPutElement(psa, &index1, &chData);
index1++;
}
else
break;
}
lngOffSet = lngOffSet + ChunkSize;
}
lngOffSet = 0;

printf("Enter a new Pub Id: ");


myscanf(pubrs.m_sz_pubid, sizeof(pubrs.m_sz_pubid));
strPubID = pubrs.m_sz_pubid;
printf("Enter descriptive text: " );
mygets(pubrs.m_sz_prinfo, sizeof(pubrs.m_sz_prinfo));

pRstPubInfo->AddNew();
pRstPubInfo->Fields->GetItem("pub_id")->PutValue(strPubID);
pRstPubInfo->Fields->GetItem("pr_info")->PutValue(pubrs.m_sz_prinfo);

// Assign the Safe array to a variant.


varChunk.vt = VT_ARRAY|VT_UI1;
varChunk.parray = psa;
hr = pRstPubInfo->Fields->GetItem("logo")->AppendChunk(varChunk);

// Update the table


pRstPubInfo->Update();

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

// Delete new record because this is demonstration.


pConnection->Execute("DELETE FROM PUB_INFO WHERE pub_id = '"
+ strPubID +"'", NULL,adCmdText);
}
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);
}

// Clean up objects before exit.


if (pRstPubInfo)
if (pRstPubInfo->State == adStateOpen)
pRstPubInfo->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;
long nCount = 0;
long i = 0;

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.

<!-- BeginExecuteJS -->


<%@LANGUAGE="JScript"%>
<%// use this meta tag instead of adojavas.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->

<%
strLastName = new String(Request.Form("AuthorLName"));

if (strLastName.indexOf("undefined") > -1)


strLastName = "";
%>

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

// command object parameters


cmdAuthor.CommandText = "SELECT * FROM Authors WHERE au_lname = ?";
cmdAuthor.Parameters.Append(cmdAuthor.CreateParameter("Last Name", adChar, adParamInput, 20,
strLastName));
strLastName));
cmdAuthor.ActiveConnection = Cnxn;

// recordset from command.execute


rsAuthor = cmdAuthor.Execute();

// recordset from connection.execute


SQLAuthor2 = "SELECT * FROM Authors";
rsAuthor2 = Cnxn.Execute(SQLAuthor2);

// check for errors


ErrCount = Cnxn.errors.count;
if(ErrCount !== 0) //write the errors
{
for(Err = 0; Err = ErrCount; Err++){
Err = Cnxn.errors.item;
Response.Write(Err);
}
// clean out any existing errors
Cnxn.Errors.Clear;
}

// show the data


Response.Write("<HR><HR>");

// 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") + " ";

// end the line


strMessage += "</P>";

// show the results


Response.Write(strMessage);

// get next record


rsAuthor.MoveNext;
}

Response.Write("<HR><HR>");

// second recordset
Response.Write("<b>Connection.Execute results</b>")
while (!rsAuthor2.EOF)
{
// start a new line
strMessage2 = "<P>";

// first and last name are in first column


strMessage2 += rsAuthor2("au_fname") + " "
strMessage2 += rsAuthor2("au_lname") + " ";

// end the line


strMessage2 += "</P>";

// show results
Response.Write(strMessage2);

// get next record


rsAuthor2.MoveNext;
}
}
}
catch (e)
{
Response.Write(e.message);
}
finally
{
// clean up
if (rsAuthor.State == adStateOpen)
rsAuthor.Close;
if (rsAuthor2.State == adStateOpen)
rsAuthor2.Close;
if (Cnxn.State == adStateOpen)
Cnxn.Close;
rsAuthor1 = null;
rsAuthor2 = null;
Cnxn = null;
}
}
%>

<hr>

<form method="POST" action="ExecuteJS.asp" id=form1 name=form1>


<p align="left">Enter last name of author to find (e.g., Ringer): <input type="text" name="AuthorLName"
size="40"></p>
<p align="left"><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2">
</p>
</form>
</body>

</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.

CONSTANT VALUE DESCRIPTION

adRecCanceled 0x100 Indicates that the record was not saved


because the operation was canceled.

adRecCantRelease 0x400 Indicates that the new record was not


saved because the existing record was
locked.

adRecConcurrencyViolation 0x800 Indicates that the record was not saved


because optimistic concurrency was in
use.

adRecDBDeleted 0x40000 Indicates that the record has already


been deleted from the data source.

adRecDeleted 0x4 Indicates that the record was deleted.

adRecIntegrityViolation 0x1000 Indicates that the record was not saved


because the user violated integrity
constraints.

adRecInvalid 0x10 Indicates that the record was not saved


because its bookmark is invalid.

adRecMaxChangesExceeded 0x2000 Indicates that the record was not saved


because there were too many pending
changes.

adRecModified 0x2 Indicates that the record was modified.

adRecMultipleChanges 0x40 Indicates that the record was not saved


because it would have affected multiple
records.

adRecNew 0x1 Indicates that the record is new.

adRecObjectOpen 0x4000 Indicates that the record was not saved


because of a conflict with an open
storage object.

adRecOK 0 Indicates that the record was


successfully updated.

adRecOutOfMemory 0x8000 Indicates that the record was not saved


because the computer has run out of
memory.
CONSTANT VALUE DESCRIPTION

adRecPendingChanges 0x80 Indicates that the record was not saved


because it refers to a pending insert.

adRecPermissionDenied 0x10000 Indicates that the record was not saved


because the user has insufficient
permissions.

adRecSchemaViolation 0x20000 Indicates that the record was not saved


because it violates the structure of the
underlying database.

adRecUnmodified 0x8 Indicates that the record was not


modified.

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.

Settings and Return Values


Sets or returns a Boolean value. The default value is True. If True, the chapter will be updated if the parent
Recordset object changes row position; if False, the chapter will continue to refer to data in the previous chapter
even though the parent Recordset object has changed row position.

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.

Settings and Return Values


Sets or returns a String value which is a command string.

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 Customers JOIN Orders ON


Customers.CustomerID = Orders.CustomerID
WHERE city = 'Seattle'
ORDER BY CustomerID

The Resync Command property is set to:

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

CREATE PROC Custorders @CustomerID char(5) AS


SELECT * FROM Customers JOIN Orders ON
Customers.CustomerID = Orders.CustomerID
WHERE Customers.CustomerID = @CustomerID

The Resync method should execute the following stored procedure:


CREATE PROC CustordersResync @ordid int AS
SELECT * FROM Customers JOIN Orders ON
Customers.CustomerID = Orders.CustomerID
WHERE Orders.ordid = @ordid

The Resync Command property is set to:

"{call CustordersResync (?)}"

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

Specifies what functionality the Supports method should test for.

CONSTANT VALUE DESCRIPTION

adAddNew 0x1000400 Supports the AddNew method to add


new records.

adApproxPosition 0x4000 Supports the AbsolutePosition and


AbsolutePage properties.

adBookmark 0x2000 Supports the Bookmark property to


gain access to specific records.

adDelete 0x1000800 Supports the Delete method to delete


records.

adFind 0x80000 Supports the Find method to locate a


row in a Recordset.

adHoldRecords 0x100 Retrieves more records or changes the


next position without committing all
pending changes.

adIndex 0x100000 Supports the Index property to name


an index.

adMovePrevious 0x200 Supports the MoveFirst and


MovePrevious methods, and Move or
GetRows methods to move the current
record position backward without
requiring bookmarks.

adNotify 0x40000 Indicates that the underlying data


provider supports notifications (which
determines whether Recordset events
are supported).

adResync 0x20000 Supports the Resync method to update


the cursor with the data that is visible in
the underlying database.

adSeek 0x200000 Supports the Seek method to locate a


row in a Recordset.

adUpdate 0x1008000 Supports the Update method to modify


existing data.

adUpdateBatch 0x10000 Supports batch updating (UpdateBatch


and CancelBatch methods) to transmit
groups of changes to the provider.
ADO/WFC Equivalent
Package: com.ms.wfc.data

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

'To integrate this code replace


'the database, DSN or Data Source values

Public Sub Main()


On Error GoTo ErrorHandler

Dim Cnxn1 As ADODB.Connection


Dim Cnxn2 As ADODB.Connection
Dim Cnxn3 As ADODB.Connection
Dim Cnxn4 As ADODB.Connection

' Open a connection without using a Data Source Name (DSN)


Set Cnxn1 = New ADODB.Connection
Cnxn1.ConnectionString = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn1.Open
MsgBox "Cnxn1 state: " & GetState(Cnxn1.State)

' Open a connection using a DSN and ODBC tags


' It is assumed that you have created DSN 'Pubs' with a user name as
' 'MyUserId' and password as 'MyPassword'.
Set Cnxn2 = New ADODB.Connection
Cnxn2.ConnectionString = "Data Source='Pubs';" & _
"User ID='MyUserId';Password='MyPassword';"
Cnxn2.ConnectionTimeout = 30
Cnxn2.Open
MsgBox "Cnxn2 state: " & GetState(Cnxn2.State)

' Open a connection using a DSN and OLE DB tags


' It is assumed that you have created DSN 'Pubs1' with windows authentication.
Set Cnxn3 = New ADODB.Connection
Cnxn3.ConnectionString = "Data Source='Pubs1';"
Cnxn3.Open
MsgBox "Cnxn2 state: " & GetState(Cnxn3.State)

' Open a connection using a DSN and individual


' arguments instead of a connection string
' It is assumed that you have created DSN 'Pubs' with a user name as
' 'MyUserId' and password as 'MyPassword'.
Set Cnxn4 = New ADODB.Connection
Cnxn4.Open "Pubs", "MyUserId", "MyPassword"
MsgBox "Cnxn4 state: " & GetState(Cnxn4.State)
MsgBox "Cnxn4 state: " & GetState(Cnxn4.State)

' 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

If Not Cnxn2 Is Nothing Then


If Cnxn2.State = adStateOpen Then Cnxn2.Close
End If
Set Cnxn2 = Nothing

If Not Cnxn3 Is Nothing Then


If Cnxn3.State = adStateOpen Then Cnxn3.Close
End If
Set Cnxn3 = Nothing

If Not Cnxn4 Is Nothing Then


If Cnxn4.State = adStateOpen Then Cnxn4.Close
End If
Set Cnxn4 = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub

Public Function GetState(intState As Integer) As String

Select Case intState


Case adStateClosed
GetState = "adStateClosed"
Case adStateOpen
GetState = "adStateOpen"
End Select

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

Indicates the text of a command to be issued against a provider.

Settings and Return Values


Gets or sets a String value that contains a provider command, such as an SQL statement, a table name, a
relative URL, or a stored procedure call. The default is the empty string ("").

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

This example demonstrates the GetString method.


Assume you are debugging a data access problem and want a quick, simple way of printing the current contents of
a small Recordset.

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

inline char* mygets(char* strDest, int n) {


char strExBuff[10];
char* pstrRet = fgets(strDest, n, stdin);

if (pstrRet == NULL)
return NULL;

// Exhaust the input buffer.


if (!strrchr(strDest, '\n'))
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;
GetStringX();
::CoUninitialize();
}

void GetStringX() {
HRESULT hr = S_OK;
char * token1;

// Define ADO object pointers.


// Initialize pointers on define.
// These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
_RecordsetPtr pRstAuthors = NULL;
// Define string variables.
_bstr_t strCnn("Provider='sqloledb'; Data Source=My_Data_Source; Initial Catalog='pubs'; Integrated
Security='SSPI';");
_bstr_t varOutput;
char *strPrompt = "Enter a state (CA, IN, KS, MD, MI, OR, TN, UT): ";
char strState[3], *pState;

try {
// Open connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));

// Open a command object for a stored procedure,


// with one parameter.
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));

printf("%s",strPrompt);
mygets(strState, 3);

pState = strtok_s(strState," \t", &token1);

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';

pConnection->Open (strCnn, "", "", adConnectUnspecified);

pRstAuthors->Open(strQry, _variant_t((IDispatch*)pConnection, true),


adOpenStatic, adLockReadOnly, adCmdText);

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);
}

// Clean up objects before exit.


if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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("\t Error number: %x\t%s", pErr->Number, pErr->Description);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);

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

Describes an Error object.

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

Specifies how a command argument should be interpreted.


It is important to validate user-supplied CommandString values to avoid giving application users the
opportunity to inject potentially dangerous commands for ADO to execute.

CONSTANT VALUE DESCRIPTION

adCmdUnspecified -1 Does not specify the command type


argument.

adCmdText 1 Evaluates CommandText as a textual


definition of a command or stored
procedure call.

adCmdTable 2 Evaluates CommandText as a table


name whose columns are all returned
by an internally generated SQL query.

adCmdStoredProc 4 Evaluates CommandText as a stored


procedure name.

adCmdUnknown 8 Default. Indicates that the type of


command in the CommandText
property is not known.

When the type of command is not


known, ADO will make several
attempts to interpret the
CommandText.

- 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.

adCmdFile 256 Evaluates CommandText as the file


name of a persistently stored
Recordset. Used with Recordset.Open
or Requery only.
CONSTANT VALUE DESCRIPTION

adCmdTableDirect 512 Evaluates CommandText as a table


name whose columns are all returned.
Used with Recordset.Open or
Requery only. To use the Seek
method, the Recordset must be
opened with adCmdTableDirect.

This value cannot be combined with


the ExecuteOptionEnum value
adAsyncExecute.

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

CommandType Property (ADO) Execute Method (ADO Command)

Execute Method (ADO Connection) Open Method (ADO Recordset)

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"

// extracts only title and type


class CTitlesRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CTitlesRs)

//Column title is the 2nd field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_szT_title, sizeof(m_szT_title), lT_titleStatus, FALSE)

// Column type is the 3rd field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(3, adVarChar, m_szT_type, sizeof(m_szT_type), lT_typeStatus, TRUE)
END_ADO_BINDING()

public:
CHAR m_szT_title[150];
ULONG lT_titleStatus;
CHAR m_szT_type[40];
ULONG lT_typeStatus;
};

inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };


void BeginTransX();
void PrintProviderError(_ConnectionPtr pConnection);

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

TESTHR(pConnection->Open(strCnn, "", "", adConnectUnspecified));

rstTitles.CreateInstance(__uuidof(Recordset));

rstTitles->CursorType = adOpenDynamic;
rstTitles->LockType = adLockPessimistic;

// open Titles table


TESTHR(rstTitles->Open("titles", _variant_t((IDispatch*)pConnection,true),
adOpenDynamic, adLockPessimistic,adCmdTable));

rstTitles->MoveFirst();
pConnection->BeginTrans();

// Open an IADORecordBinding interface pointer which


// we'll use for Binding Recordset to a class
TESTHR(rstTitles->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Bind the Recordset to a C++ Class here


TESTHR(picRs->BindToRecordset(&titlrs));

// 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));

// Check for null string.


assert(p_TempStr != NULL);

while (VARIANT_FALSE == rstTitles->EndOfFile) {


// Set the final character of the destination string to NULL.
p_TempStr[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(p_TempStr, sizeof(titlrs.m_szT_type), strtok_s(titlrs.m_szT_type," ", &token1),
sizeof(titlrs.m_szT_type) - 1);

// Compare type with psychology


if (!strcmp(p_TempStr,"psychology")) {
strTitle = titlrs.m_szT_title;
strMessage = "Title: " + strTitle + "\n Change type to Self help?(y/n)";

// Change the title for specified employee


printf("%s\n", (LPCSTR)strMessage);
do {
chKey = _getch();
} while (chKey != 'y' && chKey !='n');

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();

// Print current data in recordset.


rstTitles->Requery(0);

// Move to the first record of the title table


rstTitles->MoveFirst();
printf("\n\nPress any key to continue...");
_getch();

// Clear the screen for the next display


// system("cls");

// Open IADORecordBinding interface pointer again for binding Recordset to a class.


TESTHR(rstTitles->QueryInterface( __uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Rebind the Recordset to a C++ Class.


TESTHR(picRs->BindToRecordset(&titlrs));

while (!rstTitles->EndOfFile) {
i = i + 1;
if (i % 23 == 0) {
printf("\nPress any key to continue...");
_getch();

// Clear the screen for the next display


// system("cls");
}
printf("%s - %s\n", titlrs.m_szT_title, titlrs.m_szT_type);
rstTitles->MoveNext();
}
// Restore original data becasue this is a demonstration.
rstTitles->MoveFirst();

while (VARIANT_FALSE == rstTitles->EndOfFile) {


// Set the final character of the destination string to NULL.
p_TempStr[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(p_TempStr, sizeof(titlrs.m_szT_type), titlrs.m_szT_type, sizeof(titlrs.m_szT_type) - 1);

p_TempStr = strtok_s(p_TempStr," ", &token2);

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

printf("Source : %s\n", (LPCSTR)bstrSource);


printf("Description : %s\n", (LPCSTR)bstrDescription);
}

// Deallocate the memory


if (p_TempStr)
free(p_TempStr);
// Clean up objects before exit.
// Release the IADORecordset Interface here
if (picRs)
picRs->Release();

if (rstTitles)
if (rstTitles->State == adStateOpen)
rstTitles->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
};

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;
long nCount = 0;
long i = 0;

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

Gets or sets an OLE DB Stream object from/on an ADOStreamConstruction object.


Read/write.

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.

Settings and Return Values


Sets or returns a Long value that must be greater than 0. Default is 1.

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

Contains all the Parameter objects of a Command object.

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.parameters.Append ccmd.CreateParameter(, adInteger, adParamReturnValue, , NULL) ' return


value
ccmd.parameters.Append ccmd.CreateParameter("InParam", adVarChar, adParamInput, 20, "hello
world") ' input parameter
ccmd.parameters.Append ccmd.CreateParameter("OutParam", adVarChar, adParamOutput, 20, NULL) '
output parameter

ccmd.execute()

' Access ccmd.parameters(0) as return value of this stored procedure


' Access ccmd.parameters("OutParam") as the output parameter of this stored procedure.

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.

' Open Connection Conn


set ccmd = CreateObject("ADODB.Command")
ccmd.Activeconnection= Conn

ccmd.CommandText="SPWithParam"
ccmd.commandType = 4 'adCmdStoredProc

ccmd.parameters.Item("InParam").value = "hello world" ' input parameter


ccmd.execute()

' Access ccmd.parameters(0) as return value of stored procedure


' Access ccmd.parameters(2) or ccmd.parameters("OutParam") as the output parameter.

This section contains the following topic.


Parameters Collection Properties, Methods, and Events

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"

// This class extracts last name.


class CEmployeeRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CEmployeeRs)
// Column lname is the 4th field in the recordset
ADO_VARIABLE_LENGTH_ENTRY2(4, adVarChar, m_szau_lname,
sizeof(m_szau_lname), lau_lnameStatus, TRUE)
END_ADO_BINDING()

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();

// Clear the screen for the next display


printf("Press any key to continue...");
_getch();
system("cls");

AbsolutePosition2X();

::CoUninitialize();
}

void AbsolutePositionX() {
HRESULT hr = S_OK;

// Define ADO object pointers. // Initialize pointers on define.


// These are in the ADODB:: namespace.
_RecordsetPtr pRstEmployees = NULL;
// Define other variables. Interface Pointer declared.(VC++ Extensions)
IADORecordBinding *picRs = NULL;
CEmployeeRs emprs; // C++ class object
_bstr_t strMessage;
char chKey;

// Open a recordset using a client cursor for the Employee table.

_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated


Security='SSPI';");

try {
// Open a recordset.
TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));

// Use client cursor to enable AbsolutePosition property.


pRstEmployees->CursorLocation = adUseClient;

// Explicitly pass the default Cursor type and LockType to the recordset.
TESTHR(pRstEmployees->Open("employee", strCnn, adOpenForwardOnly, adLockReadOnly, adCmdTable));

// Open an IADORecordBinding interface pointer for binding the recordset to a class.


TESTHR(pRstEmployees->QueryInterface(__uuidof(IADORecordBinding),(LPVOID*)&picRs));

// Bind the recordset to a C++ class here.


TESTHR(picRs->BindToRecordset(&emprs));

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');

// Clear the Screen for the next output


system("cls");

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();

// GetActiveConnection returns connect string if connection


// is not open, else returns Connection object.
switch(vtConnect.vt) {
case VT_BSTR:
printf("Error:\n");
printf("Code = %08lx\n", e.Error());
printf("Message = %s\n", e.ErrorMessage());
printf("Source = %s\n", (LPCSTR) e.Source());
printf("Description = %s\n", (LPCSTR) e.Description());
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}

// Clean up objects before exit. Release the IADORecordset Interface here.


if (picRs)
picRs->Release();

if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
}

void AbsolutePosition2X() {
HRESULT hr = S_OK;

// Define ADO object pointers. Initialize pointers on define.


// These are in the ADODB:: namespace.
_RecordsetPtr pRstEmployees = NULL;

// Define Other Variables. Interface Pointer declared.(VC++ Extensions)


IADORecordBinding *picRs = NULL;
CEmployeeRs emprs; // C++ class object
_bstr_t strMessage;

// Open a recordset using a client cursor for the Employee table.


_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");

try {
// Open a recordset.
TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));

// Use client cursor to enable Absoluteposition property.


pRstEmployees->CursorLocation = adUseClient;

// Explicitly pass the default Cursor type and LockType to the Recordset.
TESTHR(pRstEmployees->Open("employee", strCnn, adOpenStatic, adLockReadOnly, adCmdTable));

// Open an IADORecordBinding interface pointer for Binding Recordset to a class.


TESTHR(pRstEmployees->QueryInterface(__uuidof(IADORecordBinding),(LPVOID*)&picRs));

// Bind the Recordset to a C++ Class here.


TESTHR(picRs->BindToRecordset(&emprs));

long lGoToPos = 21;

pRstEmployees->AbsolutePosition = (PositionEnum)lGoToPos;

// 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("\nPress any key to continue:");


_getch();
}
catch(_com_error &e) {
// Notify the user of errors if any.
_variant_t vtConnect = pRstEmployees->GetActiveConnection();

// GetActiveConnection returns connect string if connection


// is not open, else returns Connection object.
switch(vtConnect.vt) {
switch(vtConnect.vt) {
case VT_BSTR:
printf("Error:\n");
printf("Code = %08lx\n", e.Error());
printf("Message = %s\n", e.ErrorMessage());
printf("Source = %s\n", (LPCSTR) e.Source());
printf("Description = %s\n", (LPCSTR) e.Description());
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}

// Clean up objects before exit. Release the IADORecordset Interface here.


if (picRs)
picRs->Release();

if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;
long nCount = 0;
long i = 0;

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

Indicates the value assigned to a Field, Parameter, or Property object.

Settings and Return Values


Sets or returns a Variant value that indicates the value of the object. Default value depends on the Type
property.

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

Field Object Parameter Object Property Object (ADO)

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.

Settings and Return Values


Sets or returns a Variant expression that evaluates to 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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

'recordset, command and connection variables


Dim Cnxn As ADODB.Connection
Dim cmdByRoyalty As ADODB.Command
Dim prmByRoyalty As ADODB.Parameter
Dim rstByRoyalty As ADODB.Recordset
Dim rstAuthors As ADODB.Recordset
Dim strCnxn As String
Dim strSQLAuthors As String
Dim strSQLByRoyalty As String
'record variables
Dim intRoyalty As Integer
Dim strAuthorID As String

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open command object with one parameter


Set cmdByRoyalty = New ADODB.Command
cmdByRoyalty.CommandText = "byroyalty"
cmdByRoyalty.CommandType = adCmdStoredProc

' Get parameter value and append parameter


intRoyalty = Trim(InputBox("Enter royalty:"))
Set prmByRoyalty = cmdByRoyalty.CreateParameter("percentage", adInteger, adParamInput)
cmdByRoyalty.Parameters.Append prmByRoyalty
prmByRoyalty.Value = intRoyalty

' Create recordset by executing the command


Set cmdByRoyalty.ActiveConnection = Cnxn
Set rstByRoyalty = cmdByRoyalty.Execute

' 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

' Print recordset adding author names from Authors 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 & "'"
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

If Not rstAuthors Is Nothing Then


If rstAuthors.State = adStateOpen Then rstAuthors.Close
End If
Set rstAuthors = Nothing

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndAppendVB

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

Specifies the editing status of a record.

CONSTANT VALUE DESCRIPTION

adEditNone 0 Indicates that no editing operation is in


progress.

adEditInProgress 1 Indicates that data in the current record


has been modified but not saved.

adEditAdd 2 Indicates that the AddNew method has


been called, and the current record in
the copy buffer is a new record that has
not been saved in the database.

adEditDelete 4 Indicates that the current record has


been deleted.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

Dim Cnxn As ADODB.Connection


Dim rstSchema As ADODB.Recordset
Dim strCnxn As String

Set Cnxn = New ADODB.Connection


strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

Set rstSchema = Cnxn.OpenSchema(adSchemaTables)

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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndOpenSchemaVB

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

printf("Fields in Employee Table:\n\n");

// Enumerate the Fields collection of the Employees table.


pFldLoop = pRstEmployees->GetFields();
for (short int intFields = 0 ; intFields < (int)pFldLoop->GetCount() ; intFields++) {
_variant_t Index;
Index.vt = VT_I2;
Index.iVal = intFields;
printf(" Name: %s\n" , (LPCSTR) pFldLoop->GetItem(Index)->GetName());
printf(" Type: %s\n\n", (LPCTSTR)FieldType(pFldLoop->GetItem(Index)->Type));
}
}
catch (_com_error &e) {
// Display errors, if any. Pass connection pointer accessed from the Recordset.
// Display errors, if any. Pass connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstEmployees->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;
}
}

// Clean up objects before exit.


if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
}

_bstr_t FieldType(int intType) {


_bstr_t strType;
switch(intType) {
case adChar:
strType = "adChar";
break;
case adVarChar:
strType = "adVarChar";
break;
case adSmallInt:
strType = "adSmallInt";
break;
case adUnsignedTinyInt:
strType = "adUnsignedTinyInt";
break;
case adDBTimeStamp:
strType = "adDBTimeStamp";
break;
default:
break;
}
return strType;
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

Fields in Employee Table:


Name: emp_id
Type: adChar
Name: fname
Type: adVarChar
Name: minit
Type: adChar
Name: lname
Type: adVarChar
Name: job_id
Type: adSmallInt
Name: job_lvl
Type: adUnsignedTinyInt
Name: pub_id
Type: adChar
Name: hire_date
Type: adDBTimeStamp

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

Indicates whether parameter names should be passed to the provider.

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

Indicates the default database for a Connection object.

Settings and Return Values


Sets or returns a String value that evaluates to the name of a database available from the provider.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

'connection and recordset variables


Dim rstTitles As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQLTitles As String
'record variables
Dim strTitle As String
Dim strMessage As String

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' open recordset for batch uodate


Set rstTitles = New ADODB.Recordset
strSQLTitles = "titles"
rstTitles.Open strSQLTitles, Cnxn, adOpenKeyset, adLockBatchOptimistic, adCmdTable

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?"

If MsgBox(strMessage, vbYesNo) = vbYes Then


rstTitles!Type = "self_help"
End If
End If

rstTitles.MoveNext
Loop

' Ask the user if she wants to commit to all the


' changes made above.
If MsgBox("Save all changes?", vbYesNo) = vbYes Then
rstTitles.UpdateBatch
Else
rstTitles.CancelBatch
End If

' Print current data in recordset.


rstTitles.Requery
rstTitles.Requery
rstTitles.MoveFirst
Do While Not rstTitles.EOF
Debug.Print rstTitles!Title & " - " & rstTitles!Type
rstTitles.MoveNext
Loop

' Restore original values because this is a demonstration.


rstTitles.MoveFirst
Do Until rstTitles.EOF
If Trim(rstTitles!Type) = "self_help" Then
rstTitles!Type = "psychology"
End If
rstTitles.MoveNext
Loop
rstTitles.UpdateBatch

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndUpdateBatchVB

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

Specifies which records should be returned to the server.

CONSTANT VALUE DESCRIPTION

adMarshalAll 0 Default. Returns all rows to the server.

adMarshalModifiedOnly 1 Returns only modified rows to the


server.

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

Indicates the data capacity of a Field object.

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"

// Class extracts lname,fname from authors table.


class CAuthorsRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CAuthorsRs)

// Column lname is the 2nd field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_szau_lname,
sizeof(m_szau_lname), lau_lnameStatus, TRUE)

// Column fname is the 3rd field in the recordset.


ADO_VARIABLE_LENGTH_ENTRY2(3, adVarChar, m_szau_fname,
sizeof(m_szau_fname), lau_fnameStatus, TRUE)

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

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 {
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 string variables.


_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.
_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);

// Open a command object for a stored procedure, with one parameter.


TESTHR(pCmdByRoyalty.CreateInstance(__uuidof(Command)));
pCmdByRoyalty->ActiveConnection = pConnection;
pCmdByRoyalty->CommandText = "byroyalty";
pCmdByRoyalty->CommandType = adCmdStoredProc;
pCmdByRoyalty->Parameters->Refresh();

// 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);

strRoyalty = strtok_s(strTemp," \t", &token1);


if (strRoyalty == NULL) {
exit(1);
}

// if the input is not numeric then notify the user.


if (!atoi(strRoyalty)) {
printf("\nExpecting numeric value...");
continue;
}
} while (!atoi(strRoyalty));

_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);

// Open the Authors table to get author names for display.


TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
pRstAuthors->Open ("authors", _variant_t((IDispatch *) pConnection, true),
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));

// Bind the Recordset to a C++ Class here.


TESTHR(picRs->BindToRecordset(&authorsrs));

// Print current data in the recordset,adding


// author names from Authors table.
printf("Authors with %s percent royalty\n\n", strRoyalty);
while (!(pRstByRoyalty->EndOfFile)) {
_bstr_t strAuthorID = pRstByRoyalty->Fields->GetItem("au_id")->Value;

printf(" %s",(LPCSTR) (_bstr_t) pRstByRoyalty->Fields->GetItem("au_id")->Value);

pRstAuthors->Filter = "au_id ='"+strAuthorID+"'";


printf(", %s %s\n",authorsrs.lau_fnameStatus == adFldOK ?
authorsrs.m_szau_fname : "<NULL>",
authorsrs.lau_lnameStatus == adFldOK ?
authorsrs.m_szau_lname : "<NULL>");
pRstByRoyalty->MoveNext();
}
}
catch (_com_error &e) {
PrintProviderError(pConnection);
PrintComError(e);
}

if (pRstByRoyalty)
if (pRstByRoyalty->State == adStateOpen)
pRstByRoyalty->Close();
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print COM errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}
Sample Input
25

Sample Output
Authors with 25 percent royalty

724-80-9391, Stearns MacFeathe


899-46-2035, Anne Ringer

See Also
Command Object (ADO )
Parameters Collection (ADO )
Refresh Method (ADO )
Close Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Closes an open object and any dependent objects.

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.

Recordset, Record, Stream


Using the Close method to close a Recordset, Record, or Stream object releases the associated data and any
exclusive access you may have had to the data through this particular object. You can later call the Open
method to reopen the object with the same, or modified, attributes.
While a Recordset object is closed, calling any methods that require a live cursor generates an error.
If an edit is in progress while in immediate update mode, calling the Close method generates an error;
instead, call the Update or CancelUpdate method first. If you close the Recordset object while in batch update
mode, all changes since the last UpdateBatch call are lost.
If you use the Clone method to create copies of an open Recordset object, closing the original or a clone does
not affect any of the other copies.

Applies To
Connection Object (ADO) Record Object (ADO)

Recordset Object (ADO) Stream 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

Indicates the information used to establish a connection to a data source.

Settings and Return Values


Sets or returns a String value.

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

Provider= Specifies the name of a provider to use for the connection.

File Name= Specifies the name of a provider-specific file (for example, a


persisted data source object) containing preset connection
information.

Remote Provider= Specifies the name of a provider to use when opening a


client-side connection. (Remote Data Service only.)

Remote Server= Specifies the path name of the server to use when opening a
client-side connection. (Remote Data Service only.)

URL= Specifies the connection string as an absolute URL identifying


a resource, such as a file or directory.

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:

DEFAULT ADO PROVIDER WINDOWS OPERATING SYSTEM

MSDASQL Windows 2000 (32-bit)

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

Windows Vista (32-bit)

Windows Vista Service Pack 1 or later (32-bit and 64-bit)

Windows versions after Windows Vista (32-bit and 64-bit)

No default. Windows 2000 (64-bit)

When an ADO application runs on the following operating Windows XP (64-bit)


systems and does not specify the provider explicitly, ADO
returns the following error: "ADODB.Connection: provider is Windows 2003 Server (64-bit)
not specified and there is no designated default provider"
Windows Vista (64-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.

<!-- BeginExecuteVBS -->


<%@ Language=VBScript %>
<% ' use this meta tag instead of ADOVBS.inc%>
<!-- METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->
<HTML>
<HEAD>
<META name="VI60_DefaultClientScript" content=VBScript>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<title>ADO Execute Method</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>
<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

' create and open connection


Set Cnxn = Server.CreateObject("ADODB.Connection")
strCnxn="Provider='sqloledb';Data Source=" & _
Request.ServerVariables("SERVER_NAME") & ";" & _
"Integrated Security='SSPI';Initial Catalog='Northwind';"
Cnxn.Open strCnxn
' create and open recordset
Set rsCustomers = Server.CreateObject("ADODB.Recordset")
strSQLCustomers = "Customers"
rsCustomers.Open strSQLCustomers, Cnxn, adOpenKeyset, adLockOptimistic, adCmdTable

'1st Recordset using Connection - Execute


Set rsCustomers = Cnxn.Execute(strSQLCustomers)

Set Cmd = Server.CreateObject("ADODB.Command")


Cmd.ActiveConnection = Cnxn
strSQLProducts = "SELECT * From Products"
Cmd.CommandText = strSQLProducts

'2nd Recordset Cmd - execute


Set rsProducts = Cmd.Execute
%>
<TABLE COLSPAN=8 CELLPADDING=5 BORDER=0 ALIGN=CENTER>
<!-- BEGIN column header row for Customer Table-->
<TR CLASS=thead>
<TH>Company Name</TH>
<TH>Contact Name</TH>
<TH>City</TH>
</TR>

<!--Display ADO Data from Customer Table-->


<%
Do While Not rsCustomers.EOF %>
<TR CLASS=tbody>
<TD>
<%= rsCustomers("CompanyName")%>
</TD>
<TD>
<%= rsCustomers("ContactName") %>
</TD>
<TD>
<%= rsCustomers("City")%>
</TD>
</TR>
<%
rsCustomers.MoveNext
Loop
%>
</TABLE>

<HR>
<H4>Recordset Retrieved Using Command Object</H4>

<TABLE CELLPADDING=5 BORDER=0 ALIGN=CENTER WIDTH="80%">

<!-- BEGIN column header row for Product List Table-->


<TR CLASS=thead2>
<TH>Product Name</TH>
<TH>Unit Price</TH>
</TR>

<!-- Display ADO Data Product List-->


<% Do Until rsProducts.EOF %>
<TR CLASS=tbody>
<TD>
<%= rsProducts("ProductName")%>
</TD>
<TD>
<%= rsProducts("UnitPrice")%>
</TD>
<%
rsProducts.MoveNext
Loop

' 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;

// Define string variables.


_bstr_t strCnn("Provider='MSDataShape'; Data 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.
_ConnectionPtr pConnection = NULL;
_RecordsetPtr pRst = NULL;
_RecordsetPtr pRstTitleAuthor = NULL;

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

// Open recordset with names from Author & titleauthor table.


pRst->Open("SHAPE {select * from authors} "
"APPEND ({select * from titleauthor}"
"RELATE au_id TO au_id) AS chapTitleAuthor",
_variant_t((IDispatch*)pConnection, true), adOpenStatic, adLockReadOnly, adCmdText);

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);
}

// Clean up objects before exit.


if (pRst)
if (pRst->State == adStateOpen)
pRst->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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

public void cancel()


public com.ms.wfc.data.Parameter createParameter(String
Name, int Type, int Direction, int Size, Object Value)
public Recordset execute()
public Recordset execute(Object[] parameters)
public Recordset execute(Object[] parameters, int options)
public int executeUpdate(Object[] parameters)
public int executeUpdate(Object[] parameters, int options)
public int executeUpdate()

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 com.ms.wfc.data.Connection getActiveConnection()


public void setActiveConnection(com.ms.wfc.data.Connection con)
public void setActiveConnection(String conString)
public String getCommandText()
public void setCommandText(String command)
public int getCommandTimeout()
public void setCommandTimeout(int timeout)
public int getCommandType()
public void setCommandType(int type)
public String getName()
public void setName(String name)
public boolean getPrepared()
public void setPrepared(boolean prepared)
public int getState()
public com.ms.wfc.data.Parameter getParameter(int n)
public com.ms.wfc.data.Parameter getParameter(String n)
public com.ms.wfc.data.Parameters getParameters()
public AdoProperties getProperties()

See Also
Command Object (ADO )
CursorLocation Property (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Indicates the location of the cursor service.

Settings And Return Values


Sets or returns a Long value that can be set to one of the CursorLocationEnum values.

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

Connection Object (ADO) Recordset Object (ADO)

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.

Settings And Return Values


Sets or returns a MarshalOptionsEnum value. The default value is adMarshalAll.

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"

// This Class extracts only fname,lastname and hire_date


class CEmployeeRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CEmployeeRs)

// Column fname is the 2nd field in the table


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_szau_fname,
sizeof(m_szau_fname), lau_fnameStatus, FALSE)

ADO_VARIABLE_LENGTH_ENTRY2(4, adVarChar, m_szau_lname,


sizeof(m_szau_lname), lau_lnameStatus, TRUE)

ADO_VARIABLE_LENGTH_ENTRY2(8, adVarChar, m_szau_hiredate,


sizeof(m_szau_hiredate), lau_hiredateStatus, TRUE)

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;

// Define Other Variables. Interface Pointer declared.(VC++ Extensions)


// Define Other Variables. Interface Pointer declared.(VC++ Extensions)
IADORecordBinding *picRs = NULL;
CEmployeeRs emprs; // C++ class object
HRESULT hr = S_OK;
_bstr_t strMessage;

// Open a recordset using a Client Cursor for the Employee Table


_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");

try {
// Open a recordset.
TESTHR(hr = pRstEmployees.CreateInstance(__uuidof(Recordset)));

// Use client cursor to enable Absoluteposition property.


pRstEmployees->CursorLocation = adUseClient;

// Explicitly pass the default Cursor type and LockType to the Recordset here
TESTHR(hr = pRstEmployees->Open("employee", strCnn, adOpenForwardOnly, adLockReadOnly, adCmdTable));

// Open an IADORecordBinding interface pointer for Binding Recordset to a class


TESTHR(hr = pRstEmployees->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs));

// Bind the Recordset to a C++ Class here


TESTHR(hr = picRs->BindToRecordset(&emprs));

// Display Names and hire dates, five records at a time


pRstEmployees->PageSize = 5;

int intPageCount = pRstEmployees->PageCount;

for (int intPage = 1 ; intPage <= intPageCount ; intPage++ ) {


pRstEmployees->put_AbsolutePage((enum PositionEnum)intPage);
strMessage = "";

for ( int intRecord = 1 ; intRecord <= pRstEmployees->PageSize ; intRecord++ ) {


printf("\t%s %s %.10s\n",
emprs.lau_fnameStatus == adFldOK ?
emprs.m_szau_fname : "<NULL>",
emprs.lau_lnameStatus == adFldOK ?
emprs.m_szau_lname : "<NULL>",
emprs.lau_hiredateStatus == adFldOK ?
emprs.m_szau_hiredate : "<NULL>");

pRstEmployees->MoveNext();

if (pRstEmployees->EndOfFile)
break;
}
}
}
catch(_com_error &e) {
// Notify the user of errors if any.
_variant_t vtConnect = pRstEmployees->GetActiveConnection();

// GetActiveConnection returns connect string if connection


// is not open, else returns Connection object.
switch(vtConnect.vt) {
case VT_BSTR:
printf("Error:\n");
printf("Code = %08lx\n", e.Error());
printf("Message = %s\n", e.ErrorMessage());
printf("Source = %s\n", (LPCSTR) e.Source());
printf("Description = %s\n", (LPCSTR) e.Description());
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
printf("Errors occured.");
break;
}
}
// Clean up objects before exit. Release the IADORecordset Interface here
if (picRs)
picRs->Release();

if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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.

CONSTANT VALUE DESCRIPTION

adModeRead 1 Indicates read-only permissions.

adModeReadWrite 3 Indicates read/write permissions.

adModeRecursive 0x400000 Used in conjunction with the other


*ShareDeny* values
(adModeShareDenyNone,
adModeShareDenyWrite, or
adModeShareDenyRead) to
propagate sharing restrictions to all
sub-records of the current Record. It
has no affect if the Record does not
have any children. A run-time error is
generated if it is used with
adModeShareDenyNone only.
However, it can be used with
adModeShareDenyNone when
combined with other values. For
example, you can use "adModeRead
Or adModeShareDenyNone Or
adModeRecursive".

adModeShareDenyNone 16 Allows others to open a connection


with any permissions. Neither read nor
write access can be denied to others.

adModeShareDenyRead 4 Prevents others from opening a


connection with read permissions.

adModeShareDenyWrite 8 Prevents others from opening a


connection with write permissions.

adModeShareExclusive 12 Prevents others from opening a


connection.

adModeUnknown 0 Default. Indicates that the permissions


have not yet been set or cannot be
determined.

adModeWrite 2 Indicates write-only permissions.

ADO/WFC Equivalent
Package: com.ms.wfc.data
CONSTANT

AdoEnums.ConnectMode.READ

AdoEnums.ConnectMode.READWRITE

(There is no equivalent of AdoEnums.ConnectMode.RECURSIVE)

AdoEnums.ConnectMode.SHAREDENYNONE

AdoEnums.ConnectMode.SHAREDENYREAD

AdoEnums.ConnectMode.SHAREDENYWRITE

AdoEnums.ConnectMode.SHAREEXCLUSIVE

AdoEnums.ConnectMode.UNKNOWN

AdoEnums.ConnectMode.WRITE

Applies To

Mode Property (ADO) Open Method (ADO Record)

Open Method (ADO Stream) Stream Object (ADO)


Append and CreateParameter Methods Example
(JScript)
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. Cut and paste the following code to Notepad or another text editor, and save it as AppendJS.asp.

<!-- BeginAppendJS -->


<%@LANGUAGE="JScript" %>
<%// use this meta tag instead of adojavas.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->

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

// connection, recordset and command variables


var strCnxn = "Provider='sqloledb';Data Source=" + Request.ServerVariables("SERVER_NAME") + ";" +
"Initial Catalog='pubs';Integrated Security='SSPI';";
var Cnxn = Server.CreateObject("ADODB.Connection");
var cmdByRoyalty = Server.CreateObject("ADODB.Command");
var rsByRoyalty = Server.CreateObject("ADODB.Recordset");
var rsAuthor = Server.CreateObject("ADODB.Recordset");
// display variables
var strMessage;

try
{
// open connection and set cursor location
Cnxn.Open(strCnxn);
Cnxn.CursorLocation = adUseClient;

// command object initial parameters


cmdByRoyalty.CommandText = "byroyalty";
cmdByRoyalty.CommandType = adCmdStoredProc;

// create the new parameter and append to


// the Command object's parameters collection
var prmByRoyalty = cmdByRoyalty.CreateParameter("percentage", adInteger, adParamInput);
cmdByRoyalty.Parameters.Append(prmByRoyalty);
prmByRoyalty.Value = iRoyalty;

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") + "'";

// start new line


strMessage = "<P>";

// recordset data
strMessage += rsAuthor.Fields("au_fname") + " ";
strMessage += rsAuthor.Fields("au_lname") + " ";

// end the line


strMessage += "</P>";

// 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>

<form method="POST" action="AppendJS.asp" id=form1 name=form1>


<p align="left">Enter royalty percentage to find (e.g., 40): <input type="text" name="RoyaltyValue" size="5">
</p>
<p align="left"><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2">
</p>
</form>

</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

long GetCount( ); __declspec(property(get=GetCount)) long Count;


PropertyPtr GetItem( const _variant_t & Index ); __declspec(property(get=GetItem)) PropertyPtr Item[];

Errors Collection
Methods

HRESULT Clear( );
HRESULT Refresh( );

Properties

long GetCount( ); __declspec(property(get=GetCount)) long Count;


PropertyPtr GetItem( const _variant_t & Index ); __declspec(property(get=GetItem)) PropertyPtr Item[];

Parameters Collection
Methods

HRESULT Append( IDispatch * Object );


HRESULT Delete( const _variant_t & Index );
HRESULT Refresh( );

Properties

long GetCount( ); __declspec(property(get=GetCount)) long Count;


PropertyPtr GetItem( const _variant_t & Index ); __declspec(property(get=GetItem)) PropertyPtr Item[];

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

long GetCount( ); __declspec(property(get=GetCount)) long Count;


PropertyPtr GetItem( const _variant_t & Index ); __declspec(property(get=GetItem)) PropertyPtr Item[];

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.

MOVEFIRST, MOVEPREVIOUS, MOVENEX T,

MOVELAST MOVE < 0 MOVE 0 MOVE > 0

BOF=True, Allowed Error Error Allowed


EOF=False

BOF=False, Allowed Allowed Error Error


EOF=True

Both True Error Error Error Error

Both False Allowed Allowed Allowed Allowed

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

MoveFirst, MoveLast Set to True Set to True

Move 0 No change No change

MovePrevious, Move < 0 Set to True No change

MoveNext, Move > 0 No change Set to True

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.

<!-- BeginCloneVBS -->


<% Language = VBScript %>
<%' use this meta tag instead of adovbs.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->
<HTML>
<HEAD>
<TITLE>ADO Clone Method</TITLE>
</HEAD>

<BODY>

<H1 align="center">ADO Clone Method</H1>


<HR>
<% ' to integrate/test this code replace the
' Data Source value in the Connection string%>
<%
' connection and recordset variables
Dim Cnxn, strCnxn
Dim rsCustomers, strSQLCustomers
Dim rsFirst, rsLast, rsCount
Dim rsClone
Dim CloneFirst, CloneLast, CloneCount

' open connection


Set Cnxn = Server.CreateObject("ADODB.Connection")
strCnxn = "Provider='sqloledb';Data Source=" & _
Request.ServerVariables("SERVER_NAME") & ";" & _
"Integrated Security='SSPI';Initial Catalog='Northwind';"
Cnxn.Open strCnxn

' create and open Recordset using object refs


Set rsCustomers = Server.CreateObject("ADODB.Recordset")
strSQLCustomers = "Customers"

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

' create clone


' create clone
Set rsClone = rsCustomers.Clone
rsClone.MoveFirst
CloneCount = rsClone.RecordCount
CloneFirst = rsClone("CompanyName")
rsClone.MoveLast
CloneLast = rsClone("CompanyName")
%>

<!-- Display Results -->


<H3>There Are <%=rsCount%> Records in the original recordset</H3>
<H3>The first record is <%=rsFirst%> and the last record is <%=rsLast%></H3>
<BR><HR>
<H3>There Are <%=CloneCount%> Records in the original recordset</H3>
<H3>The first record is <%=CloneFirst%> and the last record is <%=CloneLast%></H3>
<BR><HR>
<H4>Location of OLEDB Database</H4>

<%
' 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.

Settings and Return Values


Sets or returns a String value that indicates the field names in the Recordset on which to sort. Each name is
separated by a comma, and is optionally followed by a blank and the keyword, ASC, which sorts the field in
ascending order, or DESC, which sorts the field in descending order. By default, if no keyword is specified, the
field is sorted in ascending 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.

<!-- BeginCacheSizeJS -->


<%@ Language="JScript" %>
<%// use this meta tag instead of adojavas.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->

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

// open a recordset on the Employee table using client-side cursor


rsCustomer.CursorLocation = adUseClient;
rsCustomer.Open("Customers", strCnxn);

// loop through the recordset 20 times


for (var i=1; i<=20; i++)
{
{
rsCustomer.MoveFirst();
while (!rsCustomer.EOF)
{
// do something with the record
var strTemp = new String(rsCustomer("CompanyName"));
rsCustomer.MoveNext();
}
}

Now = new Date();


End = Now.getTime();
NoCache = End - Start;

// cache records in groups of 30


rsCustomer.MoveFirst();
rsCustomer.CacheSize = 30;

Now = new Date();


Start = Now.getTime();

// loop through the recordset 20 times


for (var i=1; i<=20; i++)
{
rsCustomer.MoveFirst();
while (!rsCustomer.EOF)
{
// do something with the record
var strTemp = new String(rsCustomer("CompanyName"));
rsCustomer.MoveNext();
}
}

Now = new Date();


End = Now.getTime();
var Cache = End - Start;
}
catch (e)
{
Response.Write(e.message);
}
finally
{
// clean up
if (rsCustomer.State == adStateOpen)
rsCustomer.Close;
if (Cnxn.State == adStateOpen)
Cnxn.Close;
rsCustomer = null;
Cnxn = null;
}
%>

<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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

' recordset and connection variables


Dim rstEmployees As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strSQLEmployees As String
Dim strCnxn As String

Dim intLoop As Integer

' Open a connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Northwind';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open recordset with data from Employee table


Set rstEmployees = New ADODB.Recordset
strSQLEmployees = "Employee"
'rstEmployees.Open strSQLEmployee, Cnxn, , , adCmdTable
rstEmployees.Open strSQLEmployees, Cnxn, adOpenForwardOnly, adLockReadOnly, adCmdTable
'the above two lines opening the recordset are identical as
'the default values for CursorType and LockType arguments match those specified

' Print information about Fields collection


Debug.Print rstEmployees.Fields.Count & " Fields in Employee"

For intLoop = 0 To rstEmployees.Fields.Count - 1


Debug.Print " " & rstEmployees.Fields(intLoop).Name
Next intLoop

' Print information about Properties collection


Debug.Print rstEmployees.Properties.Count & " Properties in Employee"

For intLoop = 0 To rstEmployees.Properties.Count - 1


Debug.Print " " & rstEmployees.Properties(intLoop).Name
Next intLoop

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndCountVB

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.

CONSTANT VALUE DESCRIPTION

adCriteriaAllCols 1 Detects conflicts if any column of the


data source row has been changed.

adCriteriaKey 0 Detects conflicts if the key column of


the data source row has been changed,
which means that the row has been
deleted.

adCriteriaTimeStamp 3 Detects conflicts if the timestamp of the


data source row has been changed,
which means the row has been accessed
after the Recordset was obtained.

adCriteriaUpdCols 2 Detects conflicts if any of the columns


of the data source row that correspond
to updated fields of the Recordset
have been changed.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

Dim Cnxn As ADODB.Connection


Dim rstTitles As ADODB.Recordset
Dim strCnxn As String
Dim strSQLTitles As String

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Mode = adModeShareExclusive
Cnxn.IsolationLevel = adXactIsolated
Cnxn.Open strCnxn

' open Titles table


Set rstTitles = New ADODB.Recordset
strSQLTitles = "titles"
rstTitles.Open strSQLTitles, Cnxn, adOpenDynamic, adLockPessimistic, adCmdTable

Cnxn.BeginTrans

' Display connection mode


If Cnxn.Mode = adModeShareExclusive Then
MsgBox "Connection mode is exclusive."
Else
MsgBox "Connection mode is not exclusive."
End If

' Display isolation level


If Cnxn.IsolationLevel = adXactIsolated Then
MsgBox "Transaction is isolated."
Else
MsgBox "Transaction is not isolated."
End If

' Change the type of psychology titles


Do Until rstTitles.EOF
If Trim(rstTitles!Type) = "psychology" Then
rstTitles!Type = "self_help"
rstTitles.Update
End If
rstTitles.MoveNext
Loop

' Print current data in recordset


rstTitles.Requery
Do While Not rstTitles.EOF
Debug.Print rstTitles!Title & " - " & rstTitles!Type
Debug.Print rstTitles!Title & " - " & rstTitles!Type
rstTitles.MoveNext
Loop

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then
Cnxn.RollbackTrans
Cnxn.Close
End If
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndIsolationLevelVB

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

' To integrate this code replace the data source


' in the connection string

'recordset and connection variables


Dim rstEmployees As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQLEmployees As String

Dim strID As String


Dim strPrompt As String
strPrompt = "Enter an EmployeeID (e.g., 1 to 9)"

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='Microsoft.Jet.OLEDB.4.0';" & _
"Data Source='C:\Program Files\Microsoft Office XP\Office10\Samples\northwind.mdb';"
Cnxn.Open strCnxn

' open recordset server-side for indexing


Set rstEmployees = New ADODB.Recordset
rstEmployees.CursorLocation = adUseServer
strSQLEmployees = "employees"
rstEmployees.Open strSQLEmployees, strCnxn, adOpenKeyset, adLockReadOnly, adCmdTableDirect

' Does this provider support Seek and Index?


If rstEmployees.Supports(adIndex) And rstEmployees.Supports(adSeek) Then
rstEmployees.Index = "PrimaryKey"
' Display all the employees
rstEmployees.MoveFirst
Do While rstEmployees.EOF = False
Debug.Print rstEmployees!EmployeeId; ": "; rstEmployees!FirstName; " "; _
rstEmployees!LastName
rstEmployees.MoveNext
Loop

' Prompt the user for an EmployeeID between 1 and 9


rstEmployees.MoveFirst
Do
strID = LCase(Trim(InputBox(strPrompt, "Seek Example")))
' Quit if strID is a zero-length string (CANCEL, null, etc.)
If Len(strID) = 0 Then Exit Do
If Len(strID) = 1 And strID >= "1" And strID <= "9" Then
rstEmployees.Seek Array(strID), adSeekFirstEQ
If rstEmployees.EOF Then
Debug.Print "Employee not found.", , "Seek Example"
MsgBox "Employee not found."
Else
Debug.Print strID; ": Employee='"; rstEmployees!FirstName; " "; _
rstEmployees!LastName; "'"
MsgBox "EmployeeID is: " + strID + "; Employee Name is: '" + rstEmployees!FirstName + " " +
_
_
rstEmployees!LastName + "'", , "Seek Example"
End If
Else
MsgBox "You entered a wrong EmployeeID, please enter a new ID."
End If
Loop
End If

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndSeekVB

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;

// If File exists in the specified directory, then display error


if (!FileExists()) {
SaveX1();
SaveX2();
SaveX3();
}

::CoUninitialize();
}

// First, access and save the authors table.


void SaveX1() {
HRESULT hr = S_OK;

// Define ADO object pointers. Initialize pointers on define.


// These are in the ADODB:: namespace.
_RecordsetPtr pRstAuthors = NULL;

// Definitions of other variables


_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source' ; Initial Catalog='pubs'; Integrated
Security='SSPI';");

try {
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));

pRstAuthors->Open("SELECT * FROM authors",strCnn, adOpenDynamic,


adLockBatchOptimistic, adCmdText);

// For sake of illustration, save the Recordset to a diskette in XML format.


pRstAuthors->Save("c:\\pubs.xml", adPersistXML);
pRstAuthors->Save("c:\\pubs.xml", adPersistXML);
}
catch(_com_error &e) {
// Notify the user of errors, if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstAuthors->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 (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
}

// At this point, you have arrived at your destination.


// You will access the authors table as a local, disconnected Recordset.
// Don't forget you must have the MSPersist provider on the machine you
// are using in order to access the saved file, c:\pubs.xml.
void SaveX2() {
HRESULT hr = S_OK;

// Define ADO object pointers. Initialize pointers on define.


// These are in the ADODB:: namespace.
_RecordsetPtr pRstAuthors = NULL;

try {
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));

// For sake of illustration, we specify all parameters.


pRstAuthors->Open("c:\\pubs.xml", "Provider='MSPersist';", adOpenForwardOnly, adLockBatchOptimistic,
adCmdFile);

// Now you have a local, disconnected Recordset.


// (In this example, changes will not be saved).
pRstAuthors->Find("au_lname = 'Carson'", NULL, adSearchForward);
if (pRstAuthors->EndOfFile) {
printf("Name not found ...\n");
pRstAuthors->Close();
return;
}
pRstAuthors->GetFields()->GetItem("City")->PutValue("Chicago");
pRstAuthors->Update();

// 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();

// 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 (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
}

// Now update the database with changes.


void SaveX3() {
HRESULT hr = S_OK;

// Define ADO object pointers. Initialize pointers on define.


// These are in the ADODB:: namespace.
_RecordsetPtr pRstAuthors = NULL;
_ConnectionPtr pCnn = NULL;

// Definitions of other variables


_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");

try {
TESTHR(pCnn.CreateInstance(__uuidof(Connection)));

TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));

// If there is no ActiveConnection, you can open with defaults.


pRstAuthors->Open("c:\\pubs.adtg", "Provider=MSPersist;",
adOpenForwardOnly, adLockBatchOptimistic, adCmdFile);

// Connect to the database, associate the Recordset with the connection,


// then update the database table with the changed Recordset.
pCnn->Open(strCnn, "", "", NULL);

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();

// 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 (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
if (pCnn)
if (pCnn)
if (pCnn->State == adStateOpen)
pCnn->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print COM errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

bool FileExists() {
struct _finddata_t xml_file;
long hFile;

if( (hFile = _findfirst("c:\\pubs.xml", &xml_file )) != -1L)


{
printf( "File already exists!\n" );
return(true);
}
else
return (false);
}

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.

Settings and Return Values


The Dialect property contains a valid GUID that represents the dialect of the command text or stream. The
default value for this property is {C8B521FB -5CF3-11CE -ADE5-00AA0044773D }, which indicates that the
provider should choose how to interpret the command text 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.

CONSTANT VALUE DESCRIPTION

adStateClosed 0 Indicates that the object is closed.

adStateOpen 1 Indicates that the object is open.

adStateConnecting 2 Indicates that the object is connecting.

adStateExecuting 4 Indicates that the object is executing a


command.

adStateFetching 8 Indicates that the rows of the object are


being retrieved.

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

State Property (ADO MD) State Property (ADO)


Open Method (ADO Recordset)
12/10/2018 • 5 minutes to read • Edit Online

Opens a cursor on a Recordset object.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

' connection and recordset variables


Dim rstAuthors As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQLAuthors
' record variables
Dim strMessage As String
Dim intCommand As Integer

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open recordset from Authors table


Set rstAuthors = New ADODB.Recordset
rstAuthors.CursorLocation = adUseClient
' Use client cursor to enable AbsolutePosition property
strSQLAuthors = "Authors"
rstAuthors.Open strSQLAuthors, Cnxn, adOpenStatic, adLockReadOnly, adCmdTable

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

' for exiting the loop


If intCommand < 1 Or intCommand > 4 Then
MsgBox "You either entered a non-number or canceled the input box. Exit the application."
Exit Do
End If

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub

'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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

' to integrate this code replace the server name


' in the CreateObject call

' RDS variables


Dim rdsDS As RDS.DataSpace
Dim rdsDC As RDS.DataControl
Dim rdsDF As Object
' recordset and connection variables
Dim rsAuthors As ADODB.Recordset
Dim strSQLAuthors As String
Dim strCnxn As String
Dim varString As Variant

' Create a DataSpace object


Set rdsDS = New RDS.DataSpace
' Create a DataFactory object
Set rdsDF = rdsDS.CreateObject("RDSServer.DataFactory", "https://MyServer") 'MyServer

' Get all of the Author records

strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _


"Initial Catalog='Pubs';Integrated Security='SSPI';"
strSQLAuthors = "SELECT * FROM Authors"
Set rsAuthors = rdsDF.Query(strCnxn, strSQLAuthors)
' Show results
Debug.Print "Old RDS recordset count:" & rsAuthors.RecordCount

' Convert the recordset into a MIME formatted string


varString = rdsDF.ConvertToString(rsAuthors)
Debug.Print "Recordset as MIME format string:"
Debug.Print varString

' Convert string value back into an ADO Recordset


Set rdsDC = New RDS.DataControl
rdsDC.SQL = varString
rdsDC.ExecuteOptions = adcExecSync
rdsDC.FetchOptions = adcFetchUpFront
rdsDC.Refresh
' Show results
Debug.Print "New ADO recordset count:" & rdsDC.Recordset.RecordCount

' clean up
rsAuthors.Close
Set rsAuthors = Nothing
Set rdsDC = Nothing
Set rdsDS = Nothing
Set rdsDC = Nothing

ErrorHandler:

If Not rsAuthors Is Nothing Then


If Not rsAuthors Is Nothing Then
If rsAuthors.State = adStateOpen Then rsAuthors.Close
End If
Set rsAuthors = Nothing
Set rdsDC = Nothing
Set rdsDS = Nothing
Set rdsDC = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If

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

Indicates an object that contains data to be represented as a Recordset object.

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

Specifies the behavior of the CopyRecord method.

CONSTANT VALUE DESCRIPTION

adCopyAllowEmulation 4 Indicates that the Source provider


attempts to simulate the copy using
download and upload operations if this
method fails due to Destinationbeing
on a different server or is serviced by a
different provider than Source. Note
that differing provider capabilities may
hamper performance or lose data.

adCopyNonRecursive 2 Copies the current directory, but none


of its subdirectories, to the destination.
The copy operation is not recursive.

adCopyOverWrite 1 Overwrites the file or directory if the


Destination points to an existing file or
directory.

adCopyUnspecified -1 Default. Performs the default copy


operation: The operation fails if the
destination file or directory already
exists, and the operation copies
recursively.

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

' recordset variables


Dim rst As ADODB.Recordset
Dim prop As ADODB.Property
' property variables
Dim ix As Integer
Dim strMsg As String

' create client-side recordset


Set rst = New ADODB.Recordset
rst.CursorLocation = adUseClient
' enumerate property types
For ix = 0 To rst.Properties.Count - 1
Set prop = rst.Properties.Item(ix)
Select Case prop.Type
Case adBigInt
strMsg = "adBigInt"
Case adBinary
strMsg = "adBinary"
Case adBoolean
strMsg = "adBoolean"
Case adBSTR
strMsg = "adBSTR"
Case adChapter
strMsg = "adChapter"
Case adChar
strMsg = "adChar"
Case adCurrency
strMsg = "adCurrency"
Case adDate
strMsg = "adDate"
Case adDBDate
strMsg = "adDBDate"
Case adDBTime
strMsg = "adDBTime"
Case adDBTimeStamp
strMsg = "adDBTimeStamp"
Case adDecimal
strMsg = "adDecimal"
Case adDouble
strMsg = "adDouble"
Case adEmpty
strMsg = "adEmpty"
Case adError
strMsg = "adError"
Case adFileTime
strMsg = "adFileTime"
strMsg = "adFileTime"
Case adGUID
strMsg = "adGUID"
Case adIDispatch
strMsg = "adIDispatch"
Case adInteger
strMsg = "adInteger"
Case adIUnknown
strMsg = "adIUnknown"
Case adLongVarBinary
strMsg = "adLongVarBinary"
Case adLongVarChar
strMsg = "adLongVarChar"
Case adLongVarWChar
strMsg = "adLongVarWChar"
Case adNumeric
strMsg = "adNumeric"
Case adPropVariant
strMsg = "adPropVariant"
Case adSingle
strMsg = "adSingle"
Case adSmallInt
strMsg = "adSmallInt"
Case adTinyInt
strMsg = "adTinyInt"
Case adUnsignedBigInt
strMsg = "adUnsignedBigInt"
Case adUnsignedInt
strMsg = "adUnsignedInt"
Case adUnsignedSmallInt
strMsg = "adUnsignedSmallInt"
Case adUnsignedTinyInt
strMsg = "adUnsignedTinyInt"
Case adUserDefined
strMsg = "adUserDefined"
Case adVarBinary
strMsg = "adVarBinary"
Case adVarChar
strMsg = "adVarChar"
Case adVariant
strMsg = "adVariant"
Case adVarNumeric
strMsg = "adVarNumeric"
Case adVarWChar
strMsg = "adVarWChar"
Case adWChar
strMsg = "adWChar"
Case Else
strMsg = "*UNKNOWN*"
End Select
'show results
Debug.Print "Property " & ix & ": " & prop.Name & _
", Type = " & strMsg
Next ix

' clean up
Set rst = Nothing
Exit Sub

ErrorHandler:
' clean up
Set rst = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If

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

Dim ADF As RDSServer.DataFactory


Dim vntRecordShape(3)
Dim vntField1Shape(3)
Dim vntField2Shape(3)
Dim vntField3Shape(3)
Dim vntField4Shape(3)

Set ADF = New RDSServer.DataFactory

' For each field, specify the name,


' type, size, and nullability.

vntField1Shape(0) = "Name" ' Column name.


vntField1Shape(1) = CInt(129) ' Column type.
vntField1Shape(2) = CInt(40) ' Column size.
vntField1Shape(3) = False ' Nullable?

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

' Put all fields into an array of arrays.


vntRecordShape(0) = vntField1Shape
vntRecordShape(1) = vntField2Shape
vntRecordShape(2) = vntField3Shape
vntRecordShape(3) = vntField4Shape

' Use the RDSServer.DataFactory to create an empty


' recordset. It takes an array of variants where
' every element is itself another array of
' variants, one for every column required in the
' recordset.
' The elements of the inner array are the column's
' name, type, size, and nullability.
'
' NOTE: You could just use the RDS.DataControl object
' instead of the RDSServer.DataFactory object. In
' that case, the following code would be Set NewRS
' that case, the following code would be Set NewRS
' = ADC1.CreateRecordset(vntRecordShape)
Dim NewRs As ADODB.Recordset
Set NewRs = ADF.CreateRecordSet(vntRecordShape)

Dim fields(3)
fields(0) = vntField1Shape(0)
fields(1) = vntField2Shape(0)
fields(2) = vntField3Shape(0)
fields(3) = vntField4Shape(0)

' Populate the new recordset with data values.


Dim fieldVals(3)

' Use AddNew to add the records.


fieldVals(0) = "Joe"
fieldVals(1) = 5
fieldVals(2) = CDate(#1/5/1996#)
fieldVals(3) = 123.456
NewRs.AddNew fields, fieldVals

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

' Set the newly created and populated Recordset to


' the SourceRecordset property of the
' RDS.DataControl to bind to visual controls
Dim ADC1 As RDS.DataControl
Set ADC1 = New RDS.DataControl
Set ADC1.SourceRecordset = NewRs

'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

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndRsDefineShapeVB
Attributes and Name Properties Example (VC++)
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.

// 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"

// This class extracts LastName, FirstName, FaxPhone from Employees table

class CEmployeeRs : public CADORecordBinding {


BEGIN_ADO_BINDING(CEmployeeRs)

// Column LastName is the 2nd field in the table


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_szemp_LastName, sizeof(m_szemp_LastName),
lemp_LastNameStatus, TRUE)

// Column FirstName is the 17th field in the table


ADO_VARIABLE_LENGTH_ENTRY2(17, adVarChar, m_szemp_FirstName, sizeof(m_szemp_FirstName),
lemp_FirstNameStatus, TRUE)

// Column FaxPhone is the 18th field in the table


ADO_VARIABLE_LENGTH_ENTRY2(18, adVarChar, m_szemp_Faxphone, sizeof(m_szemp_Faxphone),
lemp_FaxphoneStatus, TRUE)

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;

// Define Other Variables


HRESULT hr = S_OK;
_variant_t Index;
Index.vt = VT_I2;
int j = 0;
// Open a recordset using a Client Cursor for the Employee Table
_bstr_t strCnn("Provider='sqloledb'; Data Source='(local)'; 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), adOpenForwardOnly,
adLockReadOnly, adCmdTable);

// Display the attributes of Connection.


printf("Connection attributes: %d \n", pConnection->Attributes);

// Display the attribute of the employee table's fields


printf("\nFields attributes:\n");
fldLoop = pRstEmployee->GetFields();

for (int i = 0 ; i < (int)fldLoop->GetCount() ; i++) {


Index.iVal = i;
printf (" %s = %d \n", (LPSTR)fldLoop->GetItem(Index)->GetName(),
(int)fldLoop->GetItem(Index)->GetAttributes());
}

// Display Fields of the Employee table which are NULLBALE


printf("\nNULLABLE Fields :");

for (int i1 = 0 ; i1 < (int)fldLoop->GetCount() ; i1++) {


Index.iVal = i1;

if (fldLoop->GetItem(Index)->GetAttributes() & adFldIsNullable)


printf ("%s \n", (LPSTR)fldLoop->GetItem(Index)->GetName());
}

// Display the attributes of the Employee tables's properties


printf("\nProperty attributes:\n");
proLoop = pRstEmployee->GetProperties();

for (int i2 = 0 ; i2 < (int)proLoop->GetCount() ; i2++) {


j = j + 1;
Index.iVal = i2;
printf (" %s = %d \n", (LPSTR)(_bstr_t)proLoop->GetItem(Index)->GetName(),
(int)proLoop->GetItem(Index)->GetAttributes());
}
}
catch(_com_error &e) {
// Notify the user of errors if any.

PrintProviderError(pConnection);
PrintComError(e);
}

// Clean up objects before exit.


if (pRstEmployee)
if (pRstEmployee->State == adStateOpen)
pRstEmployee->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.

// pErr is a record object in the Connection's Error collection.


ErrorPtr pErr = NULL;
long nCount = 0;
long i = 0;

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", (LPCSTR) pErr->Number, (LPCSTR) pErr->Description);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("\nError\n");
printf("Code = %08lx\n", e.Error());
printf("Code meaning = %s\n", e.ErrorMessage());
printf("Source = %s\n", (LPCSTR) bstrSource);
printf("Description = %s\n", (LPCSTR) bstrDescription);
}

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.

<!-- BeginAbsolutePageJS -->


<%@LANGUAGE="JScript" %>
<%// use this meta tag instead of adojavas.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->

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

// Open a recordset on the Employee table using


// a client-side cursor to enable AbsolutePage property.
rsEmployee.CursorLocation = adUseClient;
rsEmployee.Open("employees", strCnxn, adOpenStatic, adLockOptimistic, adCmdTable);

// 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;

// Write header information to the document


Response.Write('<p align="center">There are ' + iPageCount);
Response.Write(" pages, each containing ");
Response.Write(rsEmployee.PageSize + " or fewer records.</p>");
Response.Write('<table border="0" align="center">');
Response.Write('<tr class="thead2">');
Response.Write("<th>Page</th><th>Name</th><th>Hire Date</th></tr>");

for (var i=1; i<=iPageCount; i++)


{
rsEmployee.AbsolutePage = i;

for (iRecord = 1; iRecord <= rsEmployee.PageSize; iRecord++)


{
strMessage = "";

// Start a new table row.


strMessage = '<tr class="tbody">';

// First column in row contains page number on


// first record of each page. Otherwise, the column
// contains a non-breaking space.
if (iRecord == 1)
strMessage += "<td>Page " + i + " of " + rsEmployee.PageCount + "</td>"
else
strMessage += "<td> </td>";

// First and last name are in first column.


strMessage += "<TD>" + rsEmployee.Fields("FirstName") + " ";
strMessage += rsEmployee.Fields("LastName") + " " + "</td>";

// Hire date in second column.


strMessage += "<td>" + rsEmployee.Fields("HireDate") + "</td>";

// End the row.


strMessage += "</tr>";

// Write line to document.


Response.Write(strMessage);

// Get next record.


rsEmployee.MoveNext;

if (rsEmployee.EOF)
break;
}
}

// Finish writing table.


Response.Write("</table>");
}
catch (e)
{
Response.Write(e.message);
}
finally
{
// 'clean up
if (rsEmployee.State == adStateOpen)
rsEmployee.Close;
if (Cnxn.State == adStateOpen)
Cnxn.Close;
rsEmployee = null;
Cnxn = null;
}
%>
%>

</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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

' connection and recordset variables


Dim rstEmployees As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQLEmployees As String
' field property variables
Dim fld As ADODB.Field
Dim prp As ADODB.Property

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open recordset with data from Employees table


Set rstEmployees = New ADODB.Recordset
strSQLEmployees = "employee"
rstEmployees.Open strSQLEmployees, Cnxn, , , adCmdTable
'rstEmployees.Open strSQLEmployees, Cnxn, adOpenStatic, adLockReadOnly, adCmdTable
' the above two lines of code are identical

Debug.Print "Field values in rstEmployees"

' Enumerate the Fields collection of the Employees table


For Each fld In rstEmployees.Fields
' Because Value is the default property of a
' Field object, the use of the actual keyword
' here is optional.
Debug.Print " " & fld.Name & " = " & fld.Value
Next fld

Debug.Print "Property values in rstEmployees"

' Enumerate the Properties collection of the Recordset object


For Each prp In rstEmployees.Properties
Debug.Print " " & prp.Name & " = " & prp.Value
' because Value is the default property of a Property object
' use of the actual Value keyword is optional
Next prp

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndValueVB

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

' recordset variables


Dim rstEmployees As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim SQLEmployees As String

' open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' set recordset properties through object refs


' instead of through arguments to Open method
Set rstEmployees = New ADODB.Recordset
Set rstEmployees.ActiveConnection = Cnxn
rstEmployees.CursorLocation = adUseClient
rstEmployees.CursorType = adOpenStatic
rstEmployees.LockType = adLockBatchOptimistic

' open recordset with data from Employee table


SQLEmployees = "employee"
rstEmployees.Open SQLEmployees, , , , adCmdTable

' Show the EditMode property under different editing states


rstEmployees.AddNew
rstEmployees!emp_id = "T-T55555M"
rstEmployees!fname = "temp_fname"
rstEmployees!lname = "temp_lname"
'call function below
'to output results to debug window
EditModeOutput "After AddNew:", rstEmployees.EditMode
rstEmployees.UpdateBatch
EditModeOutput "After UpdateBatch:", rstEmployees.EditMode
rstEmployees!fname = "test"
EditModeOutput "After Edit:", rstEmployees.EditMode
rstEmployees.Close

' Delete new record because this is a demonstration


Cnxn.Execute "DELETE FROM employee WHERE emp_id = 'T-T55555M'"

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If

End Sub

Public Function EditModeOutput(strTemp As String, _


intEditMode As Integer)

' Print report based on the value of the EditMode


' property
Debug.Print strTemp
Debug.Print " EditMode = ";

Select Case intEditMode


Case adEditNone
Debug.Print "adEditNone"
Case adEditInProgress
Debug.Print "adEditInProgress"
Case adEditAdd
Debug.Print "adEditAdd"
End Select

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.

Settings and Return Values


Sets or returns a String value. The name is not case sensitive.

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.

CONSTANT VALUE DESCRIPTION

AdArray 0x2000 A flag value, always combined with


another data type constant, that
indicates an array of the other data
type. Does not apply to ADOX.

adBigInt 20 Indicates an eight-byte signed integer


(DBTYPE_I8).

adBinary 128 Indicates a binary value


(DBTYPE_BYTES).

adBoolean 11 Indicates a Boolean value


(DBTYPE_BOOL).

adBSTR 8 Indicates a null-terminated character


string (Unicode) (DBTYPE_BSTR).

adChapter 136 Indicates a four-byte chapter value that


identifies rows in a child rowset
(DBTYPE_HCHAPTER).

adChar 129 Indicates a string value (DBTYPE_STR).

adCurrency 6 Indicates a currency value (DBTYPE_CY).


Currency is a fixed-point number with
four digits to the right of the decimal
point. It is stored in an eight-byte
signed integer scaled by 10,000.

adDate 7 Indicates a date value (DBTYPE_DATE).


A date is stored as a double, the whole
part of which is the number of days
since December 30, 1899, and the
fractional part of which is the fraction of
a day.

adDBDate 133 Indicates a date value (yyyymmdd)


(DBTYPE_DBDATE).

adDBTime 134 Indicates a time value (hhmmss)


(DBTYPE_DBTIME).

adDBTimeStamp 135 Indicates a date/time stamp


(yyyymmddhhmmss plus a fraction in
billionths) (DBTYPE_DBTIMESTAMP).
CONSTANT VALUE DESCRIPTION

adDecimal 14 Indicates an exact numeric value with a


fixed precision and scale
(DBTYPE_DECIMAL).

adDouble 5 Indicates a double-precision floating-


point value (DBTYPE_R8).

adEmpty 0 Specifies no value (DBTYPE_EMPTY).

adError 10 Indicates a 32-bit error code


(DBTYPE_ERROR).

adFileTime 64 Indicates a 64-bit value representing


the number of 100-nanosecond
intervals since January 1, 1601
(DBTYPE_FILETIME).

adGUID 72 Indicates a globally unique identifier


(GUID) (DBTYPE_GUID).

adIDispatch 9 Indicates a pointer to an IDispatch


interface on a COM object
(DBTYPE_IDISPATCH).

Note This data type is currently not


supported by ADO. Usage may cause
unpredictable results.

adInteger 3 Indicates a four-byte signed integer


(DBTYPE_I4).

adIUnknown 13 Indicates a pointer to an IUnknown


interface on a COM object
(DBTYPE_IUNKNOWN).

Note This data type is currently not


supported by ADO. Usage may cause
unpredictable results.

adLongVarBinary 205 Indicates a long binary value.

adLongVarChar 201 Indicates a long string value.

adLongVarWChar 203 Indicates a long null-terminated


Unicode string value.

adNumeric 131 Indicates an exact numeric value with a


fixed precision and scale
(DBTYPE_NUMERIC).

adPropVariant 138 Indicates an Automation


PROPVARIANT
(DBTYPE_PROP_VARIANT).
CONSTANT VALUE DESCRIPTION

adSingle 4 Indicates a single-precision floating-


point value (DBTYPE_R4).

adSmallInt 2 Indicates a two-byte signed integer


(DBTYPE_I2).

adTinyInt 16 Indicates a one-byte signed integer


(DBTYPE_I1).

adUnsignedBigInt 21 Indicates an eight-byte unsigned


integer (DBTYPE_UI8).

adUnsignedInt 19 Indicates a four-byte unsigned integer


(DBTYPE_UI4).

adUnsignedSmallInt 18 Indicates a two-byte unsigned integer


(DBTYPE_UI2).

adUnsignedTinyInt 17 Indicates a one-byte unsigned integer


(DBTYPE_UI1).

adUserDefined 132 Indicates a user-defined variable


(DBTYPE_UDT).

adVarBinary 204 Indicates a binary value.

adVarChar 200 Indicates a string value.

adVariant 12 Indicates an Automation Variant


(DBTYPE_VARIANT).

Note This data type is currently not


supported by ADO. Usage may cause
unpredictable results.

adVarNumeric 139 Indicates a numeric value.

adVarWChar 202 Indicates a null-terminated Unicode


character string.

adWChar 130 Indicates a null-terminated Unicode


character string (DBTYPE_WSTR).

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

Append Method (ADO) CreateParameter Method (ADO)

CreateRecordset Method (RDS) Type Property (ADO)


Source Property (ADO Record)
10/1/2018 • 2 minutes to read • Edit Online

Indicates the data source or object represented by the Record.

Settings and Return Values


Sets or returns a Variant value that indicates the entity represented by the Record.

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;

// Define string variables.


_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;
FieldsPtr pFldLoop = NULL;
PropertiesPtr pPrpLoop = NULL;
_variant_t vtIndex;
vtIndex.vt = VT_I2;

try {
// Open recordset with data from Employee table.
TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));
pRstEmployees->Open ("employee", strCnn , adOpenForwardOnly, adLockReadOnly, adCmdTable);

printf("Field values in rstEmployees\n\n");

// Enumerate the Fields collection of the Employees table.


pFldLoop = pRstEmployees->GetFields();

for (int intFields = 0 ; intFields < (int)pFldLoop->GetCount() ; intFields++) {


vtIndex.iVal = intFields;

// Because Value is the default property of a Field object,the use of


// the actual keyword here is optional.
printf(" %s = %s\n\n" ,
(LPCSTR) pFldLoop->GetItem(vtIndex)->GetName(),
(LPCSTR) (_bstr_t) pFldLoop->GetItem(vtIndex)->Value);
}
}

printf("Property values in rstEmployees\n\n");

// Enumerate the Properties collection of the Recordset object.


pPrpLoop = pRstEmployees->GetProperties();
int intLine = 0;

for (int intProperties = 0 ; intProperties < (int)pPrpLoop->GetCount() ; intProperties++) {


vtIndex.iVal = intProperties;

// Because Value is the default property of a Property object,


// the use of the actual keyword here is optional.
_variant_t propValue = pPrpLoop->GetItem(vtIndex)->Value;
switch(propValue.vt) {

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();

// 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 (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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.

<!-- BeginMoveVBS -->


<%@ Language=VBScript %>
<%' use this meta tag instead of adovbs.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->
<HTML>
<HEAD>
<TITLE>ADO Move Methods</TITLE>
<STYLE>
<!--
BODY {
font-family: "MS SANS SERIF",sans-serif;
}
.thead1 {
background-color: #008080;
font-family: 'Arial Narrow','Arial',sans-serif;
font-size: x-small;
color: white;
}
.tbody {
text-align: center;
background-color: #f7efde;
font-family: 'Arial Narrow','Arial',sans-serif;
font-size: x-small;
}
-->
</STYLE>
</HEAD>
<BODY>
<H3>ADO Move Methods</H3>
<% ' to integrate/test this code replace the
' Data Source value in the Connection string%>
<%
' connection and recordset variables
Dim Cnxn, strCnxn
Dim rsCustomers, strSQLCustomers

' open connection


Set Cnxn = Server.CreateObject("ADODB.Connection")
strCnxn = "Provider='sqloledb';Data Source=" & _
Request.ServerVariables("SERVER_NAME") & ";" & _
"Integrated Security='SSPI';Initial Catalog='Northwind';"

Cnxn.Open strCnxn

' create and open Recordset using object refs


Set rsCustomers = Server.CreateObject("ADODB.Recordset")
Set rsCustomers = Server.CreateObject("ADODB.Recordset")
strSQLCustomers = "Customers"

rsCustomers.ActiveConnection = Cnxn
rsCustomers.CursorLocation = adUseClient
rsCustomers.CursorType = adOpenKeyset
rsCustomers.LockType = adLockOptimistic
rsCustomers.Source = strSQLCustomers
rsCustomers.Open

'Check number of user moves this session and increment by entry


Session("Clicks") = Session("Clicks") + Request.Form("MoveAmount")
Clicks = Session("Clicks")
' Move to last known recordset position plus amount passed
rsCustomers.Move CInt(Clicks)

'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
%>

<H3>Current Record Number is <BR>


<%
If Session("Clicks") = 0 Then Session("Clicks") = 1
Response.Write(Session("Clicks") )%> of <%=rsCustomers.RecordCount%></H3>
<HR>

<TABLE COLSPAN=8 CELLPADDING=5 BORDER=0>

<!-- BEGIN column header row for Customer Table-->

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

<FORM Method = Post Action="MoveVbs.asp" Name=Form>


<TABLE>
<TR>
<TD><Input Type="Button" Name=Move Value="Move Amount "></TD>
<TD></TD>
<TD><Input Type="Text" Size="4" Name="MoveAmount" Value=0></TD>
<TR>
</TABLE>
Click Move Amount to use Move Method<br>
Enter Number of Records to Move + or - </H5> </FORM>
</BODY>

<Script Language = "VBScript">


<Script Language = "VBScript">

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

Indicates the scale of numeric values in a Parameter or Field object.

Settings and Return Values


Sets or returns a Byte value that indicates the number of decimal places to which numeric values will be
resolved.

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

Parameter Object Field Object

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

Determines whether a specified Recordset object supports a particular type of functionality.

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

// The Connection events


class CConnEvent : public ConnectionEventsVt {
private:
ULONG m_cRef;

public:
CConnEvent() { m_cRef = 0; };
~CConnEvent() {};

STDMETHODIMP QueryInterface(REFIID riid, void ** ppv);


STDMETHODIMP_(ULONG) AddRef();
STDMETHODIMP_(ULONG) Release();

STDMETHODIMP raw_InfoMessage( struct Error *pError,


EventStatusEnum *adStatus,
struct _Connection *pConnection);

STDMETHODIMP raw_BeginTransComplete( LONG TransactionLevel,


struct Error *pError,
EventStatusEnum *adStatus,
struct _Connection *pConnection);
STDMETHODIMP raw_CommitTransComplete( struct Error *pError,
EventStatusEnum *adStatus,
struct _Connection *pConnection);

STDMETHODIMP raw_RollbackTransComplete( struct Error *pError,


EventStatusEnum *adStatus,
struct _Connection *pConnection);

STDMETHODIMP raw_WillExecute( BSTR *Source,


CursorTypeEnum *CursorType,
LockTypeEnum *LockType,
long *Options,
EventStatusEnum *adStatus,
struct _Command *pCommand,
struct _Recordset *pRecordset,
struct _Connection *pConnection);

STDMETHODIMP raw_ExecuteComplete( LONG RecordsAffected,


struct Error *pError,
EventStatusEnum *adStatus,
struct _Command *pCommand,
struct _Recordset *pRecordset,
struct _Connection *pConnection);

STDMETHODIMP raw_WillConnect( BSTR *ConnectionString,


BSTR *UserID,
BSTR *Password,
long *Options,
EventStatusEnum *adStatus,
struct _Connection *pConnection);

STDMETHODIMP raw_ConnectComplete( struct Error *pError,


EventStatusEnum *adStatus,
struct _Connection *pConnection);

STDMETHODIMP raw_Disconnect( EventStatusEnum *adStatus, struct _Connection *pConnection);


};

// The Recordset events


class CRstEvent : public RecordsetEventsVt {
private:
ULONG m_cRef;

public:
CRstEvent() { m_cRef = 0; };
~CRstEvent() {};

STDMETHODIMP QueryInterface(REFIID riid, void ** ppv);


STDMETHODIMP_(ULONG) AddRef();
STDMETHODIMP_(ULONG) Release();

STDMETHODIMP raw_WillChangeField( LONG cFields,


VARIANT Fields,
EventStatusEnum *adStatus,
struct _Recordset *pRecordset);

STDMETHODIMP raw_FieldChangeComplete( LONG cFields,


VARIANT Fields,
struct Error *pError,
EventStatusEnum *adStatus,
struct _Recordset *pRecordset);

STDMETHODIMP raw_WillChangeRecord( EventReasonEnum adReason,


LONG cRecords,
EventStatusEnum *adStatus,
struct _Recordset *pRecordset);

STDMETHODIMP raw_RecordChangeComplete( EventReasonEnum adReason,


LONG cRecords,
struct Error *pError,
EventStatusEnum *adStatus,
struct _Recordset *pRecordset);

STDMETHODIMP raw_WillChangeRecordset( EventReasonEnum adReason,


EventStatusEnum *adStatus,
struct _Recordset *pRecordset);

STDMETHODIMP raw_RecordsetChangeComplete( EventReasonEnum adReason,


struct Error *pError,
EventStatusEnum *adStatus,
struct _Recordset *pRecordset);

STDMETHODIMP raw_WillMove( EventReasonEnum adReason,


EventStatusEnum *adStatus,
struct _Recordset *pRecordset);

STDMETHODIMP raw_MoveComplete( EventReasonEnum adReason,


struct Error *pError,
EventStatusEnum *adStatus,
struct _Recordset *pRecordset);

STDMETHODIMP raw_EndOfRecordset( VARIANT_BOOL *fMoreData,


EventStatusEnum *adStatus,
struct _Recordset *pRecordset);

STDMETHODIMP raw_FetchProgress( long Progress,


long MaxProgress,
EventStatusEnum *adStatus,
struct _Recordset *pRecordset);

STDMETHODIMP raw_FetchComplete( struct Error *pError,


EventStatusEnum *adStatus,
struct _Recordset *pRecordset);
};

// Implement each connection method


STDMETHODIMP CConnEvent::raw_InfoMessage( struct Error *pError,
EventStatusEnum *adStatus,
struct _Connection *pConnection) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CConnEvent::raw_BeginTransComplete( LONG TransactionLevel,


struct Error *pError,
EventStatusEnum *adStatus,
struct _Connection *pConnection) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CConnEvent::raw_CommitTransComplete( struct Error *pError,


EventStatusEnum *adStatus,
struct _Connection *pConnection) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CConnEvent::raw_RollbackTransComplete( struct Error *pError,


EventStatusEnum *adStatus,
struct _Connection *pConnection) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CConnEvent::raw_WillExecute( BSTR *Source,


CursorTypeEnum *CursorType,
LockTypeEnum *LockType,
long *Options,
EventStatusEnum *adStatus,
struct _Command *pCommand,
struct _Recordset *pRecordset,
struct _Connection *pConnection) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CConnEvent::raw_ExecuteComplete( LONG RecordsAffected,


struct Error *pError,
EventStatusEnum *adStatus,
struct _Command *pCommand,
struct _Recordset *pRecordset,
struct _Connection *pConnection) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CConnEvent::raw_WillConnect( BSTR *ConnectionString,


BSTR *UserID,
BSTR *Password,
long *Options,
EventStatusEnum *adStatus,
struct _Connection *pConnection) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CConnEvent::raw_ConnectComplete( struct Error *pError,


EventStatusEnum *adStatus,
struct _Connection *pConnection) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CConnEvent::raw_Disconnect( EventStatusEnum *adStatus, struct _Connection *pConnection) {


*adStatus = adStatusUnwantedEvent;
return S_OK;
};

// Implement each recordset method


STDMETHODIMP CRstEvent::raw_WillChangeField( LONG cFields,
VARIANT Fields,
EventStatusEnum *adStatus,
struct _Recordset *pRecordset) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CRstEvent::raw_FieldChangeComplete( LONG cFields,


VARIANT Fields,
struct Error *pError,
EventStatusEnum *adStatus,
struct _Recordset *pRecordset) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CRstEvent::raw_WillChangeRecord( EventReasonEnum adReason,


LONG cRecords,
EventStatusEnum *adStatus,
struct _Recordset *pRecordset) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CRstEvent::raw_RecordChangeComplete( EventReasonEnum adReason,


STDMETHODIMP CRstEvent::raw_RecordChangeComplete( EventReasonEnum adReason,
LONG cRecords,
struct Error *pError,
EventStatusEnum *adStatus,
struct _Recordset *pRecordset) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CRstEvent::raw_WillChangeRecordset( EventReasonEnum adReason,


EventStatusEnum *adStatus,
struct _Recordset *pRecordset) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CRstEvent::raw_RecordsetChangeComplete( EventReasonEnum adReason,


struct Error *pError,
EventStatusEnum *adStatus,
struct _Recordset *pRecordset) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CRstEvent::raw_WillMove( EventReasonEnum adReason,


EventStatusEnum *adStatus,
struct _Recordset *pRecordset) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CRstEvent::raw_MoveComplete( EventReasonEnum adReason,


struct Error *pError,
EventStatusEnum *adStatus,
struct _Recordset *pRecordset) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CRstEvent::raw_EndOfRecordset( VARIANT_BOOL *fMoreData,


EventStatusEnum *adStatus,
struct _Recordset *pRecordset) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CRstEvent::raw_FetchProgress( long Progress,


long MaxProgress,
EventStatusEnum *adStatus,
struct _Recordset *pRecordset) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CRstEvent::raw_FetchComplete( struct Error *pError,


EventStatusEnum *adStatus,
struct _Recordset *pRecordset) {
*adStatus = adStatusUnwantedEvent;
return S_OK;
};

STDMETHODIMP CRstEvent::QueryInterface(REFIID riid, void ** ppv) {


*ppv = NULL;
if (riid == __uuidof(IUnknown) || riid == __uuidof(RecordsetEventsVt))
*ppv = this;

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;
}

STDMETHODIMP CConnEvent::QueryInterface(REFIID riid, void ** ppv) {


*ppv = NULL;
if (riid == __uuidof(IUnknown) || riid == __uuidof(ConnectionEventsVt))
*ppv = this;

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;

// Start using the Connection events


hr = pConn->QueryInterface(__uuidof(IConnectionPointContainer), (void **)&pCPC);

if (FAILED(hr))
return rc;

hr = pCPC->FindConnectionPoint(__uuidof(ConnectionEvents), &pCP);
hr = pCPC->FindConnectionPoint(__uuidof(ConnectionEvents), &pCP);
pCPC->Release();

if (FAILED(hr))
return rc;

pConnEvent = new CConnEvent();


hr = pConnEvent->QueryInterface(__uuidof(IUnknown), (void **) &pUnk);

if (FAILED(hr))
return rc;

hr = pCP->Advise(pUnk, &dwConnEvt);
pCP->Release();

if (FAILED(hr))
return rc;

// Start using the Recordset events


hr = pRst->QueryInterface(__uuidof(IConnectionPointContainer), (void **)&pCPC);

if (FAILED(hr))
return rc;

hr = pCPC->FindConnectionPoint(__uuidof(RecordsetEvents), &pCP);
pCPC->Release();

if (FAILED(hr))
return rc;

pRstEvent = new CRstEvent();


hr = pRstEvent->QueryInterface(__uuidof(IUnknown), (void **) &pUnk);

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();

// Stop using the Connection events


hr = pConn->QueryInterface(__uuidof(IConnectionPointContainer), (void **) &pCPC);

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;

// Stop using the Recordset events


hr = pRst->QueryInterface(__uuidof(IConnectionPointContainer), (void **) &pCPC);

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.

This section contains the following topic.


Errors Collection Properties, Methods, and Events

See Also
Error Object
Appendix A: Providers
StringFormatEnum
10/1/2018 • 2 minutes to read • Edit Online

Specifies the format when retrieving a Recordset as a string.

CONSTANT VALUE DESCRIPTION

adClipString 2 Delimits rows by RowDelimiter,


columns by ColumnDelimiter, and null
values by NullExpr. These three
parameters of the GetString method
are valid only with a StringFormat of
adClipString.

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

Deletes an entity represented by a Record.

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

Deletes an object from the Fields collection.

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

Dim cnn As New ADODB.Connection


Dim cat As New ADOX.Catalog
Dim colTemp As New ADOX.Column
Dim rstEmployees As New Recordset
Dim strMessage As String
Dim strInput As String
Dim tblEmp As ADOX.Table

' Connect the catalog.


cnn.Open "Provider='Microsoft.Jet.OLEDB.4.0';data source=" & _
"'Northwind.mdb';"
Set cat.ActiveConnection = cnn

Set tblEmp = cat.Tables("Employees")

' Create a new Field object and append it to the Fields


' collection of the Employees table.
colTemp.Name = "FaxPhone"
colTemp.Type = adVarWChar
colTemp.DefinedSize = 24
colTemp.Attributes = adColNullable
cat.Tables("Employees").Columns.Append colTemp.Name, adWChar, 24

' Open the Employees table for updating as a Recordset


rstEmployees.Open "Employees", cnn, adOpenKeyset, adLockOptimistic, adCmdTable

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

' Print report.


Debug.Print "Name - Fax number"
Debug.Print !FirstName & " " & !LastName & " - ";

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:

If Not rstEmployees Is Nothing Then


If rstEmployees.State = adStateOpen Then rstEmployees.Close
End If
Set rstEmployees = Nothing

If Not tblEmp Is Nothing Then tblEmp.Columns.Delete colTemp.Name

Set cat = Nothing


Set colTemp = Nothing

If Not cnn Is Nothing Then


If cnn.State = adStateOpen Then cnn.Close
End If
Set cnn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If

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;

_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated


Security='SSPI';");

// Initialize pointers on define. These are in the ADODB:: namespace.


_RecordsetPtr pRstAuthors = NULL;
_variant_t vTarget;
_bstr_t strAns;
_bstr_t strTitle;
strTitle = "CompareBookmarks Example";
try {
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));

pRstAuthors->Open("SELECT * FROM authors ORDER BY au_id", strCnn, adOpenStatic, adLockReadOnly,


adCmdText);

long count = pRstAuthors->RecordCount;


printf("Rows in the Recordset = %d\n", count);
if (count == 0)
exit(1); // Exit if an empty recordset

srand( (unsigned)time( NULL ) ); // Randomize

count = int(rand() % (count-1)); // Get position between 1 and count-1


if (!count)
count++;
printf("Randomly chosen row position = %d\n", count);
_variant_t vtBookMark = (short)adBookmarkFirst;
pRstAuthors->Move(count,vtBookMark); // Move row to random position

vTarget = pRstAuthors->Bookmark; // Remember the mystery row.


count = 0;
pRstAuthors->MoveFirst();

while (!(pRstAuthors->EndOfFile)) { // Loop through recordset


long result = pRstAuthors->CompareBookmarks(pRstAuthors->Bookmark, vTarget);

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();

// 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;
}
}

// Clean up objects before exit.


if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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;

_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.
_ConnectionPtr pConnection = NULL;

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

catch (_com_error &e) {


// Notify the user of errors if any.
PrintProviderError(pConnection);
PrintComError(e);
}

if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

See Also
Connection Object (ADO )
Version Property (ADO )
UpdateBatch Method
10/1/2018 • 2 minutes to read • Edit Online

Writes all pending batch updates to disk.

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

This example demonstrates the ActiveCommand property.


A subroutine is given a Recordset object whose ActiveCommand property is used to display the command text
and parameter that created the Recordset.
'BeginActiveCommandVB

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

'recordset and connection variables


Dim cmd As ADODB.Command
Dim rst As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
'record variables
Dim strPrompt As String
Dim strName As String

Set Cnxn = New ADODB.Connection


Set cmd = New ADODB.Command

strPrompt = "Enter an author's name (e.g., Ringer): "


strName = Trim(InputBox(strPrompt, "ActiveCommandX Example"))
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"

'create SQL command string


cmd.CommandText = "SELECT * FROM Authors WHERE au_lname = ?"
cmd.Parameters.Append cmd.CreateParameter("LastName", adChar, adParamInput, 20, strName)

Cnxn.Open strCnxn
cmd.ActiveConnection = Cnxn

'create the recordset by executing command string


Set rst = cmd.Execute(, , adCmdText)
'see the results
Call ActiveCommandXprint(rst)

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndActiveCommandVB

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)

Dim strName As String

strName = rstp.ActiveCommand.Parameters.Item("LastName").Value

Debug.Print "Command text = '"; rstp.ActiveCommand.CommandText; "'"


Debug.Print "Parameter = '"; strName; "'"

If rstp.BOF = True Then


Debug.Print "Name = '"; strName; "', not found."
Else
Debug.Print "Name = '"; rstp!au_fname; " "; rstp!au_lname; _
"', author ID = '"; rstp!au_id; "'"
End If

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.

<!-- BeginActualSizeJS -->


<%@LANGUAGE="JScript" %>
<%// use this meta tag instead of adojavas.inc%>
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->
<html>

<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">

<h1>ADO ActualSize and DefinedSize 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 rsSuppliers = Server.CreateObject("ADODB.Recordset");
// display variables
var fld, strMessage;

try
{
// open connection
Cnxn.Open(strCnxn);

// Open a recordset on the stores table


rsSuppliers.Open("Suppliers", strCnxn);

// build table headers


Response.Write("<table>");
Response.Write('<tr class="thead2"><th>Field Value</th>');
Response.Write('<tr class="thead2"><th>Field Value</th>');
Response.Write("<th>Defined Size</th>");
Response.Write("<th>Actual Size</th></tr>");

while (!rsSuppliers.EOF)
{
// start a new line
strMessage = '<tr class="tbody">';

// Display the contents of the chosen field with


// its defined size and actual size
fld = rsSuppliers("CompanyName");
strMessage += '<td align="left">' + fld.Value + "</td>"
strMessage += "<td>" + fld.DefinedSize + "</td>";
strMessage += "<td>" + fld.ActualSize + "</td>";

// end the line


strMessage += "</tr>";

// display data
Response.Write(strMessage);

// get next record


rsSuppliers.MoveNext;

}
// 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

Specifies the type of data stored in a Stream object.

CONSTANT VALUE DESCRIPTION

adTypeBinary 1 Indicates binary data.

adTypeText 2 Default. Indicates text data, which is in


the character set specified by Charset.

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.

CONSTANT VALUE DESCRIPTION CONSTRAINT COLUMNS

adSchemaAsserts 0 Returns the assertions CONSTRAINT_CATALOG


defined in the catalog that CONSTRAINT_SCHEMA
are owned by a given user. CONSTRAINT_NAME

(ASSERTIONS Rowset)

adSchemaCatalogs 1 Returns the physical CATALOG_NAME


attributes associated with
catalogs accessible from the
DBMS.

(CATALOGS Rowset)

adSchemaCharacterSets 2 Returns the character sets CHARACTER_SET_CATALOG


defined in the catalog that CHARACTER_SET_SCHEMA
are accessible to a given CHARACTER_SET_NAME
user.

(CHARACTER_SETS Rowset)

adSchemaCheckConstrain 5 Returns the check CONSTRAINT_CATALOG


ts constraints defined in the CONSTRAINT_SCHEMA
catalog that are owned by a CONSTRAINT_NAME
given user.

(CHECK_CONSTRAINTS)
Rowset)
CONSTANT VALUE DESCRIPTION CONSTRAINT COLUMNS

adSchemaCollations 3 Returns the character COLLATION_CATALOG


collations defined in the COLLATION_SCHEMA
catalog that are accessible to COLLATION_NAME
a given user.

(COLLATIONS Rowset)

adSchemaColumnPrivileg 13 Returns the privileges on TABLE_CATALOG


es columns of tables defined in TABLE_SCHEMA
the catalog that are available TABLE_NAME
to, or granted by, a given COLUMN_NAME GRANTOR
user. GRANTEE

(COLUMN_PRIVILEGES
Rowset)

adSchemaColumns 4 Returns the columns of TABLE_CATALOG


tables (including views) TABLE_SCHEMA
defined in the catalog that TABLE_NAME
are accessible to a given COLUMN_NAME
user.

(COLUMNS Rowset)

adSchemaColumnsDomai 11 Returns the columns defined DOMAIN_CATALOG


nUsage in the catalog that are DOMAIN_SCHEMA
dependent on a domain DOMAIN_NAME
defined in the catalog and COLUMN_NAME
owned by a given user.

(COLUMN_DOMAIN_USAGE
Rowset)

adSchemaConstraintColu 6 Returns the columns used TABLE_CATALOG


mnUsage by referential constraints, TABLE_SCHEMA
unique constraints, check TABLE_NAME
constraints, and assertions, COLUMN_NAME
defined in the catalog and
owned by a given user.

(CONSTRAINT_COLUMN_US
AGE Rowset)

adSchemaConstraintTable 7 Returns the tables that are TABLE_CATALOG


Usage used by referential TABLE_SCHEMA
constraints, unique TABLE_NAME
constraints, check
constraints, and assertions
defined in the catalog and
owned by a given user.

(CONSTRAINT_TABLE_USAG
E Rowset)
CONSTANT VALUE DESCRIPTION CONSTRAINT COLUMNS

adSchemaCubes 32 Returns information about CATALOG_NAME


the available cubes in a SCHEMA_NAME
schema (or the catalog, if CUBE_NAME
the provider does not
support schemas).

(CUBES Rowset*)

adSchemaDBInfoKeyword 30 Returns a list of provider- <None>


s specific keywords.

(IDBInfo::GetKeywords)

adSchemaDBInfoLiterals 31 Returns a list of provider- <None>


specific literals used in text
commands.

(IDBInfo::GetLiteralInfo)

adSchemaDimensions 33 Returns information about CATALOG_NAME


the dimensions in a given SCHEMA_NAME
cube. It has one row for CUBE_NAME
each dimension. DIMENSION_NAME
DIMENSION_UNIQUE_NAM
(DIMENSIONS Rowset) E

adSchemaForeignKeys 27 Returns the foreign key PK_TABLE_CATALOG


columns defined in the PK_TABLE_SCHEMA
catalog by a given user. PK_TABLE_NAME
FK_TABLE_CATALOG
(FOREIGN_KEYS Rowset) FK_TABLE_SCHEMA
FK_TABLE_NAME

adSchemaHierarchies 34 Returns information about CATALOG_NAME


the hierarchies available in a SCHEMA_NAME
dimension. CUBE_NAME
DIMENSION_UNIQUE_NAM
(HIERARCHIES Rowset) E HIERARCHY_NAME
HIERARCHY_UNIQUE_NAME

adSchemaIndexes 12 Returns the indexes defined TABLE_CATALOG


in the catalog that are TABLE_SCHEMA
owned by a given user. INDEX_NAME TYPE
TABLE_NAME
(INDEXES Rowset)

adSchemaKeyColumnUsa 8 Returns the columns defined CONSTRAINT_CATALOG


ge in the catalog that are CONSTRAINT_SCHEMA
constrained as keys by a CONSTRAINT_NAME
given user. TABLE_CATALOG
TABLE_SCHEMA
(KEY_COLUMN_USAGE TABLE_NAME
Rowset) COLUMN_NAME
CONSTANT VALUE DESCRIPTION CONSTRAINT COLUMNS

adSchemaLevels 35 Returns information about CATALOG_NAME


the levels available in a SCHEMA_NAME
dimension. CUBE_NAME
DIMENSION_UNIQUE_NAM
(LEVELS Rowset) E
HIERARCHY_UNIQUE_NAME
LEVEL_NAME
LEVEL_UNIQUE_NAME

adSchemaMeasures 36 Returns information about CATALOG_NAME


the available measures. SCHEMA_NAME
CUBE_NAME
(MEASURES Rowset) MEASURE_NAME
MEASURE_UNIQUE_NAME

adSchemaMembers 38 Returns information about CATALOG_NAME


the available members. SCHEMA_NAME
CUBE_NAME
(MEMBERS Rowset) DIMENSION_UNIQUE_NAM
E
HIERARCHY_UNIQUE_NAME
LEVEL_UNIQUE_NAME
LEVEL_NUMBER
MEMBER_NAME
MEMBER_UNIQUE_NAME
MEMBER_CAPTION
MEMBER_TYPE Tree
operator. For more
information, see OLE DB for
Online Analytical Processing
(OLAP).

adSchemaPrimaryKeys 28 Returns the primary key PK_TABLE_CATALOG


columns defined in the PK_TABLE_SCHEMA
catalog by a given user. PK_TABLE_NAME

(PRIMARY_KEYS Rowset)

adSchemaProcedureColu 29 Returns information about PROCEDURE_CATALOG


mns the columns of rowsets PROCEDURE_SCHEMA
returned by procedures. PROCEDURE_NAME
COLUMN_NAME
(PROCEDURE_COLUMNS
Rowset)

adSchemaProcedurePara 26 Returns information about PROCEDURE_CATALOG


meters the parameters and return PROCEDURE_SCHEMA
codes of procedures. PROCEDURE_NAME
PARAMETER_NAME
(PROCEDURE_PARAMETERS
Rowset)

adSchemaProcedures 16 Returns the procedures PROCEDURE_CATALOG


defined in the catalog that PROCEDURE_SCHEMA
are owned by a given user. PROCEDURE_NAME
PROCEDURE_TYPE
(PROCEDURES Rowset)
CONSTANT VALUE DESCRIPTION CONSTRAINT COLUMNS

adSchemaProperties 37 Returns information about CATALOG_NAME


the available properties for SCHEMA_NAME
each level of the dimension. CUBE_NAME
DIMENSION_UNIQUE_NAM
(PROPERTIES Rowset) E
HIERARCHY_UNIQUE_NAME
LEVEL_UNIQUE_NAME
MEMBER_UNIQUE_NAME
PROPERTY_TYPE
PROPERTY_NAME

adSchemaProviderSpecifi -1 Used if the provider defines <Provider specific>


c its own nonstandard schema
queries.

adSchemaProviderTypes 22 Returns the (base) data DATA_TYPE BEST_MATCH


types supported by the data
provider.

(PROVIDER_TYPES Rowset)

AdSchemaReferentialCons 9 Returns the referential CONSTRAINT_CATALOG


traints constraints defined in the CONSTRAINT_SCHEMA
catalog that are owned by a CONSTRAINT_NAME
given user.

(REFERENTIAL_CONSTRAINT
S Rowset)

adSchemaSchemata 17 Returns the schemas CATALOG_NAME


(database objects) that are SCHEMA_NAME
owned by a given user. SCHEMA_OWNER

(SCHEMATA Rowset)

adSchemaSQLLanguages 18 Returns the conformance <None>


levels, options, and dialects
supported by the SQL-
implementation processing
data defined in the catalog.

(SQL_LANGUAGES Rowset)

adSchemaStatistics 19 Returns the statistics defined TABLE_CATALOG


in the catalog that are TABLE_SCHEMA
owned by a given user. TABLE_NAME

(STATISTICS Rowset)

adSchemaTableConstraint 10 Returns the table constraints CONSTRAINT_CATALOG


s defined in the catalog that CONSTRAINT_SCHEMA
are owned by a given user. CONSTRAINT_NAME
TABLE_CATALOG
(TABLE_CONSTRAINTS TABLE_SCHEMA
Rowset) TABLE_NAME
CONSTRAINT_TYPE
CONSTANT VALUE DESCRIPTION CONSTRAINT COLUMNS

adSchemaTablePrivileges 14 Returns the privileges on TABLE_CATALOG


tables defined in the catalog TABLE_SCHEMA
that are available to, or TABLE_NAME GRANTOR
granted by, a given user. GRANTEE

(TABLE_PRIVILEGES Rowset)

adSchemaTables 20 Returns the tables (including TABLE_CATALOG


views) defined in the catalog TABLE_SCHEMA
that are accessible to a given TABLE_NAME TABLE_TYPE
user.

(TABLES Rowset)

adSchemaTranslations 21 Returns the character TRANSLATION_CATALOG


translations defined in the TRANSLATION_SCHEMA
catalog that are accessible to TRANSLATION_NAME
a given user.

(TRANSLATIONS Rowset)

adSchemaTrustees 39 Reserved for future use.

adSchemaUsagePrivileges 15 Returns the USAGE OBJECT_CATALOG


privileges on objects defined OBJECT_SCHEMA
in the catalog that are OBJECT_NAME
available to, or granted by, a OBJECT_TYPE GRANTOR
given user. GRANTEE

(USAGE_PRIVILEGES Rowset)

adSchemaViewColumnUsa 24 Returns the columns on VIEW_CATALOG


ge which viewed tables, defined VIEW_SCHEMA VIEW_NAME
in the catalog and owned by
a given user, are dependent.

(VIEW_COLUMN_USAGE
Rowset)

adSchemaViews 23 Returns the views defined in TABLE_CATALOG


the catalog that are TABLE_SCHEMA
accessible to a given user. TABLE_NAME

(VIEWS Rowset)

adSchemaViewTableUsag 25 Returns the tables on which VIEW_CATALOG


e viewed tables, defined in the VIEW_SCHEMA VIEW_NAME
catalog and owned by a
given user, are dependent.

(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.

CONSTANT VALUE DESCRIPTION

adPromptAlways 1 Prompts always.

adPromptComplete 2 Prompts if more information is required.

adPromptCompleteRequired 3 Prompts if more information is required


but optional parameters are not
allowed.

adPromptNever 4 Never prompts.

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

Indicates the maximum number of records to return to a Recordset from a query.

Settings and Return Values


Sets or returns a Long value that indicates the maximum number of records to return. Default is zero (0), which
means no limit.

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.

Settings and Return Values


Sets or returns a Byte value that indicates the maximum number of digits used to represent values.

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

Field Object Parameter Object

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

Deletes the current record or a group of records.

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

Contains all the Property objects for a specific instance of an object.

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.

Settings and Return Values


Sets or returns a String value, which is the name of the index.

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;

// 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';");

// Define ADO object pointers. Initialize pointers on define.


// These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
_ConnectionPtr pConnection2 = NULL;
_CommandPtr pCmdChange = NULL;
_CommandPtr pCmdRestore = NULL;

try {
// Open two asynchronous connections,displaying a message while connecting.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
TESTHR(pConnection2.CreateInstance(__uuidof(Connection)));

pConnection->Open (strCnn, "", "", adAsyncConnect);


while(pConnection->State == adStateConnecting)
printf("Opening first connection....\n\n");

pConnection2->Open (strCnn, "", "", adAsyncConnect);


while(pConnection2->State == adStateConnecting)
printf("Opening second connection....\n\n");

// Create two command objects.


TESTHR(pCmdChange.CreateInstance(__uuidof(Command)));
pCmdChange->ActiveConnection = pConnection;
pCmdChange->CommandText = strSQLChange;
TESTHR(pCmdRestore.CreateInstance(__uuidof(Command)));
pCmdRestore->ActiveConnection = pConnection2;
pCmdRestore->CommandText = strSQLRestore;

// Executing the commands,displaying a message while they are executing.


pCmdChange->Execute(NULL,NULL,adAsyncExecute);
while(pCmdChange->State == adStateExecuting)
printf("Change command executing...\n\n");

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();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

See Also
State Property (ADO )
AffectEnum
1/8/2019 • 2 minutes to read • Edit Online

Specifies which records are affected by an operation.

CONSTANT VALUE DESCRIPTION

adAffectAll 3 If there is not a Filter applied to the


Recordset, affects all records.

If the Filter property is set to a string


criteria (such as "Author='Smith'"), then
the operation affects visible records in
the current chapter.

If the Filter property is set to a


member of the FilterGroupEnum or an
array of bookmarks, then the operation
will affect all rows of the Recordset.
Note: adAffectAll is hidden in the
Visual Basic Object Browser.

adAffectAllChapters 4 Affects all records in all sibling chapters


of the Recordset, including those not
visible via any Filter that is currently
applied.

adAffectCurrent 1 Affects only the current record.

adAffectGroup 2 Affects only records that satisfy the


current Filter property setting. You
must set the Filter property to a
FilterGroupEnum value or an array of
Bookmarks to use this option.

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)

Resync Method UpdateBatch Method


WillMove and MoveComplete Events (ADO)
10/1/2018 • 2 minutes to read • Edit Online

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"

// This class extracts title_id and type from titles table.


class CTitleRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CTitleRs)
// Column title_id is the 1st field in the table
ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, m_szt_Title_id, sizeof(m_szt_Title_id), lt_Title_idStatus,
FALSE)

// Column type is the 3rd field in the table


ADO_VARIABLE_LENGTH_ENTRY2(3, adVarChar, m_szt_Type, sizeof(m_szt_Type), lt_TypeStatus, TRUE)

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;

// Define string variables.


_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.
IADORecordBinding *picRs = NULL; // Interface Pointer Declared
CTitleRs titlers; // C++ Class Object
_RecordsetPtr pRstTitles = NULL;
_RecordsetPtr pRstTitles = NULL;
LPSTR p_TempStr = NULL;
char * token1;

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

// Open an IADORecordBinding interface pointer which


// we will use for binding Recordset to a class.
TESTHR(hr = pRstTitles->QueryInterface(__uuidof(IADORecordBinding),(LPVOID*)&picRs));

// Bind the Recordset to a C++ class here


TESTHR(hr = picRs->BindToRecordset(&titlers));

p_TempStr = (LPSTR) malloc(sizeof(titlers.m_szt_Type));

// Change the type of psychology titles.


while (!(pRstTitles->EndOfFile)) {
// Set the final character of the destination string to NULL.
p_TempStr[sizeof(titlers.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(p_TempStr, sizeof(titlers.m_szt_Type), strtok_s(titlers.m_szt_Type, " ", &token1),
sizeof(titlers.m_szt_Type) - 1);

// Compare the type of psychology titles


if (!strcmp(p_TempStr,"psychology"))
// Copy "self_help" title field
pRstTitles->Fields->GetItem("type")->Value = (_bstr_t) ("self_help");
pRstTitles->MoveNext();
}

// Display Title ID and status


pRstTitles->MoveFirst();
while ( !(pRstTitles->EndOfFile) ) {
if ( pRstTitles->Status == adRecModified )
printf("%s - Modified\n",titlers.lt_Title_idStatus == adFldOK ? titlers.m_szt_Title_id : "
<NULL>");
else
printf("%s\n",titlers.lt_Title_idStatus == adFldOK ? titlers.m_szt_Title_id : "<NULL>");
pRstTitles->MoveNext();
}
}

catch (_com_error &e) {


// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstTitles->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;
}
}

// Deallocate the memory


// Deallocate the memory
if (p_TempStr)
free(p_TempStr);

if (pRstTitles)
if (pRstTitles->State == adStateOpen) {
// Cancel the update because this is a demonstration.
pRstTitles->CancelBatch(adAffectAll);
pRstTitles->Close();
}
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Dim Cnxn As ADODB.Connection


Dim rstTitles As ADODB.Recordset
Dim fldType As ADODB.Field
Dim strCnxn As String
Dim strSQLTitles As String

' Open connection.


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Open recordset for batch update


' using object refs to set properties
Set rstTitles = New ADODB.Recordset
Set rstTitles.ActiveConnection = Cnxn
rstTitles.CursorType = adOpenKeyset
rstTitles.LockType = adLockBatchOptimistic
strSQLTitles = "titles"
rstTitles.Open strSQLTitles

' Set field object variable for Type field


Set fldType = rstTitles!Type

' Change the type of psychology titles


Do Until rstTitles.EOF
If Trim(fldType) = "psychology" Then
fldType = "self_help"
End If
rstTitles.MoveNext
Loop

' Similate a change by another user by updating


' data using a command string
Cnxn.Execute "UPDATE Titles SET type = 'sociology' " & _
"WHERE type = 'psychology'"

'Check for changes


rstTitles.MoveFirst
Do Until rstTitles.EOF
If fldType.OriginalValue <> fldType.UnderlyingValue Then
MsgBox "Data has changed!" & vbCr & vbCr & _
" Title ID: " & rstTitles!title_id & vbCr & _
" Current value: " & fldType & vbCr & _
" Original value: " & _
fldType.OriginalValue & vbCr & _
fldType.OriginalValue & vbCr & _
" Underlying value: " & _
fldType.UnderlyingValue & vbCr
End If
rstTitles.MoveNext
Loop

' Cancel the update because this is a demonstration


rstTitles.CancelBatch

' Restore original values


Cnxn.Execute "UPDATE Titles SET type = 'psychology' " & _
"WHERE type = 'sociology'"

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndOriginalValueVB

See Also
OriginalValue Property (ADO )
Recordset Object (ADO )
UnderlyingValue Property
Delete Method (ADO Parameters Collection)
11/28/2018 • 2 minutes to read • Edit Online

Deletes an object from the Parameters collection.

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

This example demonstrates the GetString method.


Assume you are debugging a data access problem and want a quick, simple way of printing the current contents of
a small Recordset.

'BeginGetStringVB

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

' connection variables


Dim Cnxn As ADODB.Connection
Dim rstAuthors As ADODB.Recordset
Dim strCnxn As String
Dim strSQLAuthors As String
Dim varOutput As Variant

' specific variables


Dim strPrompt As String
Dim strState As String

' open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' get user input


strPrompt = "Enter a state (CA, IN, KS, MD, MI, OR, TN, UT): "
strState = Trim(InputBox(strPrompt, "GetString Example"))

' open recordset


Set rstAuthors = New ADODB.Recordset
strSQLAuthors = "SELECT au_fname, au_lname, address, city FROM Authors " & _
"WHERE state = '" & strState & "'"
rstAuthors.Open strSQLAuthors, Cnxn, adOpenStatic, adLockReadOnly, adCmdText

If Not rstAuthors.EOF Then


' Use all defaults: get all rows, TAB as column delimiter,
' CARRIAGE RETURN as row delimiter, EMPTY-string as null delimiter
varOutput = rstAuthors.GetString(adClipString)
' print output
Debug.Print "State = '" & strState & "'"
Debug.Print "Name Address City" & vbCr
Debug.Print varOutput
Else
Debug.Print "No rows found for state = '" & strState & "'" & vbCr
End If

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndGetStringVB

See Also
GetString Method (ADO )
Recordset Object (ADO )
GetRows Method (ADO)
10/1/2018 • 2 minutes to read • Edit Online

Retrieves multiple records of a Recordset object into an array.

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

Moves the position of the current record in a Recordset object.

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

' recordset and connection variables


Dim rstTitles As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQLTitles As String
' array variables
Dim arrCursorType(4) As Integer
Dim intIndex As Integer

' open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' Fill array with CursorType constants


arrCursorType(0) = adOpenForwardOnly
arrCursorType(1) = adOpenKeyset
arrCursorType(2) = adOpenDynamic
arrCursorType(3) = adOpenStatic

' open recordset using each CursorType and optimistic locking


For intIndex = 0 To 3
Set rstTitles = New ADODB.Recordset
rstTitles.CursorType = arrCursorType(intIndex)
rstTitles.LockType = adLockOptimistic

strSQLTitles = "Titles"
rstTitles.Open strSQLTitles, Cnxn, , , adCmdTable

Select Case arrCursorType(intIndex)


Case adOpenForwardOnly
Debug.Print "ForwardOnly cursor supports:"
Case adOpenKeyset
Debug.Print "Keyset cursor supports:"
Case adOpenDynamic
Debug.Print "Dynamic cursor supports:"
Case adOpenStatic
Debug.Print "Static cursor supports:"
End Select

' call the DisplaySupport procedure from below


' to display the supported options
DisplaySupport rstTitles

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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndSupportsVB

'BeginSupports2VB
Public Sub DisplaySupport(rstTemp As ADODB.Recordset)

Dim arrConstants(11) As Long


Dim blnSupports As Boolean
Dim intIndex As Integer

' Fill array with cursor option constants


arrConstants(0) = adAddNew
arrConstants(1) = adApproxPosition
arrConstants(2) = adBookmark
arrConstants(3) = adDelete
arrConstants(4) = adFind
arrConstants(5) = adHoldRecords
arrConstants(6) = adMovePrevious
arrConstants(7) = adNotify
arrConstants(8) = adResync
arrConstants(9) = adUpdate
arrConstants(10) = adUpdateBatch

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub OpenX()


On Error GoTo ErrorHandler

Dim Cnxn As ADODB.Connection


Dim rstEmployees As ADODB.Recordset
Dim strCnxn As String
Dim strSQLEmployees As String
Dim varDate As Variant

' Open connection


strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Set Cnxn = New ADODB.Connection
Cnxn.Open strCnxn

' Open employee table


Set rstEmployees = New ADODB.Recordset
strSQLEmployees = "employee"
rstEmployees.Open strSQLEmployees, Cnxn, adOpenKeyset, adLockOptimistic, adCmdTable

' Assign the first employee record's hire date


' to a variable, then change the hire date
varDate = rstEmployees!hire_date
Debug.Print "Original data"
Debug.Print " Name - Hire Date"
Debug.Print " " & rstEmployees!fname & " " & _
rstEmployees!lname & " - " & rstEmployees!hire_date
rstEmployees!hire_date = #1/1/1900#
rstEmployees.Update
Debug.Print "Changed data"
Debug.Print " Name - Hire Date"
Debug.Print " " & rstEmployees!fname & " " & _
rstEmployees!lname & " - " & rstEmployees!hire_date

' Requery Recordset and reset the hire date


rstEmployees.Requery
rstEmployees!hire_date = varDate
rstEmployees.Update
Debug.Print "Data after reset"
Debug.Print " Name - Hire Date"
Debug.Print " " & rstEmployees!fname & " " & _
rstEmployees!lname & " - " & rstEmployees!hire_date

' 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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndOpenVB

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

Indicates whether to save a compiled version of a Command before execution.

Settings and Return Values


Sets or returns a Boolean value that, if set to True, indicates that the command should be prepared.

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

Indicates the name of the provider for a Connection object.

Settings and Return Values


Sets or returns a String value that indicates the provider name.

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)

// Column au_id is the 1st field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_au_fname, sizeof(m_au_fname), lemp_fnameStatus, TRUE)
ADO_VARIABLE_LENGTH_ENTRY2(3, adVarChar, m_au_lname, sizeof(m_au_lname), lemp_lnameStatus, TRUE)
ADO_VARIABLE_LENGTH_ENTRY2(4, adVarChar, m_au_city, sizeof(m_au_city), lemp_cityStatus, TRUE)
ADO_VARIABLE_LENGTH_ENTRY2(5, adChar, m_au_state, sizeof(m_au_state), lemp_stateStatus, TRUE)
END_ADO_BINDING()

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

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 {
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;

// Define Other Variables


IADORecordBinding *picRs = NULL; // Interface Pointer declared
CAuthorsRs authorsrs; // C++ class object
HRESULT hr = S_OK;

// Open Authors table


_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");

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->Open("SELECT au_id, au_fname, au_lname, city, "


"state FROM Authors ORDER BY au_lname", strCnn, adOpenStatic, adLockReadOnly, adCmdText);

// Open an IADORecordBinding interface pointer which we'll use


// for Binding Recordset to a class.
TESTHR(pRstAuthors->QueryInterface(__uuidof(IADORecordBinding),(LPVOID*)&picRs));

// Bind the Recordset to a C++ Class here.


TESTHR(picRs->BindToRecordset(&authorsrs));

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>");

printf("Enter number of records to Move \n(positive or negative, 0 (zero) to quit): ");


mygets(strTemp, 5);

strMove = strtok_s(strTemp, "\t", &token1);

if (strMove == NULL || *strMove == '0')


break;
// if the input is not numeric then notify the user.
if (!atol(strMove)) {
printf("Expecting numeric value...\n");
continue;
}

// Store bookmark in case the Move goes too far forward or backward.
_variant_t varBookmark = pRstAuthors->Bookmark;

// Move method requires parameter of data type Long.


long lngMove = atol(strMove);

pRstAuthors->Move(lngMove);

// Trap for BOF or EOF.


if (pRstAuthors->BOF) {
printf("Too far backward! Returning to current record.\n");
pRstAuthors->Bookmark = varBookmark;
}

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();

// 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;
}

// Clean up objects before exit. Release the IADORecordset Interface here


if (picRs)
picRs->Release();

if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

Sample Input
1
0

Sample Output
Record 1 of 23
Author: Abraham Bennet
Location: Berkeley, CA

Enter number of records to Move


(positive or negative, Enter to quit): Record 2 of 23
Author: Reginald Blotchet-Halls
Location: Corvallis, OR

Enter number of records to Move


(positive or negative, Enter to quit):

See Also
Move Method (ADO )
ADO Events
1/25/2019 • 2 minutes to read • Edit Online

BeginTransComplete Called after the BeginTrans operation.

CommitTransComplete Called after the CommitTrans operation.

ConnectComplete Called after a connection starts.

Disconnect Called after a connection ends.

EndOfRecordset Called when there is an attempt to move to a row past the


end of the Recordset.

ExecuteComplete Called after a command has finished executing.

FetchComplete Called after all the records in a lengthy asynchronous


operation have been retrieved into the Recordset.

FetchProgress Called periodically during a lengthy asynchronous operation


to report how many rows have currently been retrieved into
the Recordset.

FieldChangeComplete Called after the value of one or more Field objects has
changed.

InfoMessage Called whenever a warning occurs during a


ConnectionEvent operation.

MoveComplete Called after the current position in the Recordset changes.

RecordChangeComplete Called after one or more records change.

RecordsetChangeComplete Called after the Recordset has changed.

RollbackTransComplete Called after the RollbackTrans operation.

WillChangeField Called before a pending operation changes the value of one


or more Field objects in the Recordset.

WillChangeRecord Called before one or more records (rows) in the Recordset


change.

WillChangeRecordset Called before a pending operation changes the Recordset.

WillConnect Called before a connection starts.


WillExecute Called just before a pending command executes on this
connection and affords the user an opportunity to examine
and modify the pending execution parameters.

WillMove The WillMove event is called before a pending operation


changes the current position in the Recordset.

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

#define TESTHR(x) if FAILED(x) _com_issue_error(x)

#include <stdio.h>
#include <ole2.h>
#include "conio.h"
#include "icrsint.h"

// class extracts fname,lastname


class CEmployeeRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CEmployeeRs)

// Column au_id is the 1st field in the recordset


ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, m_szau_id, sizeof(m_szau_id),
lau_idStatus, TRUE)

ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_szau_lname, sizeof(m_szau_lname),


lau_lnameStatus, TRUE)

ADO_VARIABLE_LENGTH_ENTRY2(3, adVarChar, m_szau_fname, sizeof(m_szau_fname),


lau_fnameStatus, TRUE)

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;

// Define Other variables


IADORecordBinding *picRs = NULL; // Interface Pointer declared.(VC++ Extensions) TCS(SPA)
CEmployeeRs emprs; // C++ class object TCS(SPA)
_bstr_t strAuthorId;
int intRoyalty;
VARIANT vtroyal;

_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated


Security='SSPI';");

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;

// Define stored procedure's input parameter.


printf("Enter Royalty : ");
scanf_s("%d",&intRoyalty);

// Assign Integer value


vtroyal.vt = VT_I2;
vtroyal.iVal = intRoyalty;

TESTHR(pPrmByRoyalty.CreateInstance(__uuidof(Parameter)));
pPrmByRoyalty->Type = adInteger;
pPrmByRoyalty->Size = 3;
pPrmByRoyalty->Direction = adParamInput;
pPrmByRoyalty->Value = vtroyal;
pCmdByRoyalty->Parameters->Append(pPrmByRoyalty);

// Create a recordset by executing a command.


pRstByRoyalty = pCmdByRoyalty->Execute(NULL,NULL,adCmdStoredProc);

// Open the authors table to get author names for display.


TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
hr = pRstAuthors->Open("authors", strCnn, 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));

// Bind the Recordset to a C++ Class here


TESTHR(picRs->BindToRecordset(&emprs));

// 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 + "'";

printf("\n\t%s, %s %s",emprs.lau_idStatus == adFldOK ? emprs.m_szau_id : "<NULL>",\


emprs.lau_fnameStatus == adFldOK ? emprs.m_szau_fname : "<NULL>",\
emprs.lau_lnameStatus == adFldOK ? emprs.m_szau_lname : "<NULL>");

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);
}

// Clean up objects before exit. Release the IADORecordset Interface here


if (picRs)
picRs->Release();

if (pRstByRoyalty)
if (pRstByRoyalty->State == adStateOpen)
pRstByRoyalty->Close();
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;
long nCount = 0;
long i = 0;

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

Dim rstRoySched As ADODB.Recordset


Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQLRoySched As String

Dim strMsg As String


Dim strTitleID As String
Dim intLoRange As Integer
Dim intHiRange As Integer
Dim intRoyalty As Integer

' open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' open RoySched table with cursor client-side


Set rstRoySched = New ADODB.Recordset
rstRoySched.CursorLocation = adUseClient
rstRoySched.CursorType = adOpenStatic
rstRoySched.LockType = adLockBatchOptimistic
rstRoySched.Open "SELECT * FROM roysched WHERE royalty = 20", strCnxn, , , adCmdText

' Prompt for a record to delete


strMsg = "Before delete there are " & rstRoySched.RecordCount & _
" titles with 20 percent royalty:" & vbCr & vbCr

Do While Not rstRoySched.EOF


strMsg = strMsg & rstRoySched!title_id & vbCr
rstRoySched.MoveNext
Loop

strMsg = strMsg & vbCr & vbCr & "Enter the ID of a record to delete:"
strTitleID = UCase(InputBox(strMsg))

If strTitleID = "" Then


Err.Raise 1, , "You didn't enter any value for the record ID."
End If

' Move to the record and save data so it can be restored


rstRoySched.Filter = "title_id = '" & strTitleID & "'"

If rstRoySched.RecordCount < 1 Then


Err.Raise 1, , "There is no record for the record ID you entered."
End If

intLoRange = rstRoySched!lorange
intHiRange = rstRoySched!hirange
intHiRange = rstRoySched!hirange
intRoyalty = rstRoySched!royalty

' Delete the record


rstRoySched.Delete
rstRoySched.UpdateBatch

' Show the results


rstRoySched.Filter = adFilterNone
rstRoySched.Requery
strMsg = ""
strMsg = "After delete there are " & rstRoySched.RecordCount & _
" titles with 20 percent royalty:" & vbCr & vbCr
Do While Not rstRoySched.EOF
strMsg = strMsg & rstRoySched!title_id & vbCr
rstRoySched.MoveNext
Loop
MsgBox strMsg

' Restore the data because this is a demonstration


rstRoySched.AddNew
rstRoySched!title_id = strTitleID
rstRoySched!lorange = intLoRange
rstRoySched!hirange = intHiRange
rstRoySched!royalty = intRoyalty
rstRoySched.UpdateBatch

' 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

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndDeleteVB

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

Command Object (ADO) Connection Object (ADO) Record Object (ADO)

Recordset Object (ADO) Stream Object (ADO)

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.

Settings and Return Values


Sets or returns a LineSeparatorsEnum value that indicates the line separator character used in the Stream. The
default value is adCRLF.

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

AbsolutePage Indicates on which page the current record resides.

AbsolutePosition Indicates the ordinal position of the current record of a


Recordset object.

ActiveCommand Indicates the Command object that created the associated


Recordset object.

ActiveConnection Indicates to which Connection object the specified


Command, Recordset, or Record object currently belongs.

ActualSize Indicates the actual length of a field's value.

Attributes Indicates one or more characteristics of an object.

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.

Bookmark 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.

CacheSize Indicates the number of records from a Recordset object


that are cached locally in memory.

Chapter Gets or sets an OLE DB Chapter object from/on an


ADORecordsetConstruction object.

CharSet Indicates the character set into which the contents of a text
Stream should be translated.

CommandStream Indicates the stream used as the input to a Command


object.

CommandText Indicates the text of a command to be issued against a


provider.

CommandTimeout Indicates how long to wait while executing a command


before terminating the attempt and generating an error.

CommandType Indicates the type of a Command object.


ConnectionString Property Indicates the information used to establish a connection to a
data source.

ConnectionTimeout Indicates how long to wait while establishing a connection


before terminating the attempt and generating an error.

Count Indicates the number of objects in a collection.

CursorLocation Indicates the location of the cursor service.

CursorType Indicates the type of cursor used in a Recordset object.

DataMember Indicates the name of the data member that will be retrieved
from the object referenced by the DataSource property.

DataSource Indicates an object that contains data to be represented as a


Recordset object.

DefaultDatabase Indicates the default database for a Connection object.

DefinedSize Indicates the data capacity of a Field object.

Description Describes an Error object.

Dialect Indicates the syntax and general rules that the provider will
use to parse the CommandText or CommandStream
properties.

Direction Indicates whether the Parameter represents an input


parameter, an output parameter, or both, or if the parameter
is the return value from a stored procedure.

EditMode Indicates the editing status of the current record.

EOS Indicates whether the current position is at the end of the


stream.

Filter Indicates a filter for data in a Recordset.

HelpContext and HelpFile Indicates the Help file and topic associated with an Error
object.

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 of a Help file.

Index Indicates the name of the index currently in effect for a


Recordset object.

IsolationLevel Indicates the level of isolation for a Connection object.


Item Indicates a specific member of a collection, by name or
ordinal number.

LineSeparator Indicates the binary character to be used as the line


separator in text Stream objects.

LockType Indicates the type of locks placed on records during editing.

MarshalOptions Indicates which records are to be marshaled back to the


server.

MaxRecords Indicates the maximum number of records to return to a


Recordset from a query.

Mode Indicates the available permissions for modifying data in a


Connection, Record, or Stream object.

Name Indicates the name of an object.

NativeError Indicates the provider-specific error code for a particular


Error object.

Number Indicates the number that uniquely identifies an Error object.

NumericScale Indicates the scale of numeric values in a Parameter or Field


object.

OriginalValue Indicates the value of a Field that existed in the record


before any changes were made.

PageCount Indicates how many pages of data the Recordset object


contains.

PageSize Indicates how many records represent one page in the


Recordset.

ParentRow 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.

ParentURL Indicates an absolute URL string that points to the parent


Record of the current Record object.

Position Indicates the current position within a Stream object.

Precision Indicates the degree of precision for numeric values in a


Parameter object or for numeric Field objects.

Prepared Indicates whether to save a compiled version of a command


before execution.

Provider Indicates the name of the provider for a Connection object.

RecordCount Indicates the number of records in a Recordset object.


RecordType Indicates the type of Record object.

Row Gets or sets an OLE DB Row object from/on an


ADORecordConstruction object.

RowPosition Gets or sets an OLE DB RowPosition object from/on an


ADORecordsetConstruction object.

Rowset Gets or sets an OLE DB Rowset object from/on an


ADORecordsetConstruction 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

SQLState Indicates the SQL state for a specific Error 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 Field) Indicates the status of a Field object.

Status (ADO Recordset) Indicates the status of the current record regarding batch
updates or other bulk operations.

StayInSync 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.

Stream Property Gets or sets an OLE DB Stream object from/on an


ADOStreamConstruction object.

Type Indicates the operational type or data type of a Parameter,


Field, or Property object.

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.

Value Indicates the value assigned to a Field, Parameter, or


Property object.

Version Indicates the ADO version number.

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

Skips one entire line when reading a text Stream.

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

Removes all the Error objects from the Errors collection.

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;

// Define string variables.


_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 and hire dates from employee table.
TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));

pRstEmployees->Open("SELECT fName, lName, hire_date "


"FROM Employee ORDER BY lName",strCnn, adOpenStatic, adLockReadOnly, adCmdText);

while (true) { // continuous loop


int intLines = 0;

// Get user input for number of rows.


printf("Enter number of rows to retrieve (0 to exit): ");
int intRows;
scanf_s("%d", &intRows);
if (intRows <= 0)
break;

// If GetRowsOK is successful, print the results,


// noting if the end of the file was reached.
_variant_t avarRecords;

if (GetRowsOK(pRstEmployees, intRows, avarRecords)) {


long lUbound;
HRESULT hr = SafeArrayGetUBound(avarRecords.parray, 2, &lUbound);

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

// Print the retrieved data.


for (int intRecords = 0 ; intRecords < lUbound+1 ; intRecords++) {
long rgIndices[2];
rgIndices[0] = 0;
rgIndices[1] = intRecords;
_variant_t result;
result.vt = VT_BSTR;

hr = SafeArrayGetElement(avarRecords.parray, rgIndices, &result);

if (hr == 0)
printf("%s ",(LPCSTR)(_bstr_t)result);

rgIndices[0] = 1;

hr = SafeArrayGetElement(avarRecords.parray, rgIndices, &result);

if (hr == 0)
printf("%s, ",(LPCSTR)(_bstr_t)result);

rgIndices[0] = 2;

hr = SafeArrayGetElement(avarRecords.parray, rgIndices, &result);

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();

// 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;
}
}

// Clean up objects before exit.


if (pRstEmployees)
if (pRstEmployees->State == adStateOpen)
pRstEmployees->Close();
}

bool GetRowsOK(_RecordsetPtr pRstTemp,int intNumber, _variant_t& avarData) {


// Store results of GetRows method in array.
avarData = pRstTemp->GetRows(intNumber);

// 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;
}
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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

Specifies the type of cursor used in a Recordset object.

CONSTANT VALUE DESCRIPTION

adOpenDynamic 2 Uses a dynamic cursor. Additions,


changes, and deletions by other users
are visible, and all types of movement
through the Recordset are allowed,
except for bookmarks, if the provider
doesn't support them.

adOpenForwardOnly 0 Default. Uses a forward-only cursor.


Identical to a static cursor, except that
you can only scroll forward through
records. This improves performance
when you need to make only one pass
through a Recordset.

adOpenKeyset 1 Uses a keyset cursor. Like a dynamic


cursor, except that you can't see
records that other users add, although
records that other users delete are
inaccessible from your Recordset. Data
changes by other users are still visible.

adOpenStatic 3 Uses a static cursor, which is a static


copy of a set of records that you can
use to find data or generate reports.
Additions, changes, or deletions by
other users are not visible.

adOpenUnspecified -1 Does not specify the type of cursor.

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 CancelBatch( enum AffectEnum AffectRecords );

HRESULT CancelUpdate( );

_RecordsetPtr Clone( enum LockTypeEnum LockType );

HRESULT Close( );

enum CompareEnum CompareBookmarks( const _variant_t


& Bookmark1, const _variant_t & Bookmark2 );

HRESULT Delete( enum AffectEnum AffectRecords );

HRESULT Find( _bstr_t Criteria, long SkipRecords, enum


SearchDirectionEnum SearchDirection, const _variant_t & Start =
vtMissing );

_variant_t GetRows( long Rows, const _variant_t & Start =


vtMissing, const _variant_t & Fields = vtMissing );

_bstr_t GetString( enum


StringFormatEnum StringFormat, long NumRows, _bstr_t
ColumnDelimeter, _bstr_t RowDelimeter, _bstr_t NullExpr );

HRESULT Move( long NumRecords, const _variant_t & Start =


vtMissing );

HRESULT MoveFirst( );
HRESULT MoveLast( );
HRESULT MoveNext( );
HRESULT MovePrevious( );

_RecordsetPtr NextRecordset( VARIANT * RecordsAffected );

HRESULT Open( const _variant_t & Source, const _variant_t &


ActiveConnection, enum CursorTypeEnum CursorType, enum LockTypeEnum
LockType, long Options );

HRESULT Requery( long Options );

HRESULT Update( const _variant_t & Fields = vtMissing, const


_variant_t & Values = vtMissing );

HRESULT UpdateBatch( enum AffectEnum AffectRecords );

HRESULT Resync( enum AffectEnum AffectRecords, enum


ResyncEnum ResyncValues );

HRESULT Save( const _variant_t & Destination, enum


PersistFormatEnum PersistFormat );

HRESULT Seek( const _variant_t & KeyValues, enum SeekEnum


SeekOption );

VARIANT_BOOL Supports( enum CursorOptionEnum CursorOptions );

Properties
enum PositionEnum GetAbsolutePage( );
void PutAbsolutePage( enum PositionEnum pl );
__declspec(property(get=GetAbsolutePage,put=PutAbsolutePage)) enum
PositionEnum AbsolutePage;

enum PositionEnum GetAbsolutePosition( );


void PutAbsolutePosition( enum PositionEnum pl );
__declspec(property(get=GetAbsolutePosition,put=PutAbsolutePosition))
enum PositionEnum AbsolutePosition;

IDispatchPtr GetActiveCommand( );
__declspec(property(get=GetActiveCommand)) IDispatchPtr ActiveCommand;

void PutRefActiveConnection( IDispatch * pvar );


void PutActiveConnection( const _variant_t & pvar );
_variant_t GetActiveConnection( );

enum CursorLocationEnum GetCursorLocation( );


void PutCursorLocation( enum CursorLocationEnum plCursorLoc );
__declspec(property(get=GetCursorLocation,put=PutCursorLocation)) enum
CursorLocationEnum CursorLocation;

VARIANT_BOOL GetBOF( );
__declspec(property(get=GetBOF)) VARIANT_BOOL BOF;

VARIANT_BOOL GetEndOfFile( ); // Actually, GetEOF. Renamed in #import.


__declspec(property(get=GetEndOfFile)) VARIANT_BOOL EndOfFile;

_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;

enum CursorTypeEnum GetCursorType( );


void PutCursorType( enum CursorTypeEnum plCursorType );
__declspec(property(get=GetCursorType,put=PutCursorType)) enum
CursorTypeEnum CursorType;

_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;

enum EditModeEnum GetEditMode( );


__declspec(property(get=GetEditMode)) enum EditModeEnum EditMode;

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;

enum LockTypeEnum GetLockType( );


void PutLockType( enum LockTypeEnum plLockType );
__declspec(property(get=GetLockType,put=PutLockType)) enum LockTypeEnum
LockType;
LockType;

enum MarshalOptionsEnum GetMarshalOptions( );


void PutMarshalOptions( enum MarshalOptionsEnum peMarshal );
__declspec(property(get=GetMarshalOptions,put=PutMarshalOptions)) enum
MarshalOptionsEnum MarshalOptions;

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;

void PutRefSource( IDispatch * pvSource );


void PutSource( _bstr_t pvSource );
_variant_t GetSource( );

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

Dim File As ADODB.Record


Dim strFile As String
Dim Cnxn As ADODB.Connection
Dim strCnxn As String

Set Cnxn = New ADODB.Connection


strCnxn = "url=https://MyServer/"
Cnxn.Open strCnxn

Set File = New ADODB.Record


strFile = "Folder/FileName"
' Open a read/write document
File.Source = strFile
File.ActiveConnection = Cnxn
File.Mode = adModeReadWrite
File.Open

Debug.Print "Append a couple of fields"

File.Fields.Append "chektest:fld1", adWChar, 42, adFldUpdatable, "fld1"


File.Fields.Append "chektest:fld2", adWChar, 42, adFldUpdatable, "fld2"

Debug.Print "status for the fields"


Debug.Print File.Fields("chektest:fld1").Status 'adfldpendinginsert
Debug.Print File.Fields("chektest:fld2").Status 'adfldpendinginsert

'turn off error-handling to verify field status


On Error Resume Next

File.Fields.Update

Debug.Print "Update succeeds"


Debug.Print File.Fields("chektest:fld1").Status 'adfldpendinginsert + adFieldUnavailable
Debug.Print File.Fields("chektest:fld2").Status 'adfldpendinginsert + adFieldUnavailable

' resume default error-handling


On Error GoTo 0

' 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.

Attribute VB_Name = "StatusField"

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.

Attribute VB_Name = "StatusField"

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

'To integrate this code


'replace the data source and initial catalog values
'in the connection string

Public Sub Main()


On Error GoTo ErrorHandler

' connection and recordset variables


Dim Cnxn As New ADODB.Connection
Dim rstAuthors As New ADODB.Recordset
Dim strCnxn As String
Dim strSQLAuthors As String

Dim strTitle As String

' Open connection


Set Cnxn = New ADODB.Connection
strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Cnxn.Open strCnxn

' open client-side recordset to enable sort method


Set rstAuthors = New ADODB.Recordset
rstAuthors.CursorLocation = adUseClient
strSQLAuthors = "SELECT * FROM Authors"
rstAuthors.Open strSQLAuthors, Cnxn, adOpenStatic, adLockReadOnly, adCmdText

' sort the recordset last name ascending


rstAuthors.Sort = "au_lname ASC, au_fname ASC"
' show output
Debug.Print "Last Name Ascending:"
Debug.Print "First Name Last Name" & vbCr

rstAuthors.MoveFirst
Do Until rstAuthors.EOF
Debug.Print rstAuthors!au_fname & " " & rstAuthors!au_lname
rstAuthors.MoveNext
Loop

' sort the recordset last name descending


rstAuthors.Sort = "au_lname DESC, au_fname ASC"
' show output
Debug.Print "Last Name Descending"
Debug.Print "First Name Last Name" & vbCr

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

If Not Cnxn Is Nothing Then


If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing

If Err <> 0 Then


MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndSortVB

This is the secondary utility routine that prints the given title, and the contents of the specified Recordset.

Attribute VB_Name = "Sort"

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

Indicates the SQL state for a given Error object.

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

Axes Collection Columns Collection CubeDefs Collection


Dimensions Collection Errors Collection Fields Collection

Groups Collection Hierarchies Collection Indexes Collection

Keys Collection Levels Collection Members Collection

Parameters Collection Positions Collection Procedures Collection

Properties Collection Tables Collection Users Collection

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

2. Query the IADORecordsetConstruction interface on the Recordset object:

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

public void append(com.ms.wfc.data.Parameter param)


public void delete(int n)
public void delete(String s)
public void refresh()
public Parameter getItem(int n)
public Parameter getItem(String s)

Properties

public int getCount()

Fields
Methods

public void append(String name, int type)


public void append(String name, int type, int definedSize)
public void append(String name, int type, int definedSize, int attrib)
public void delete(int n)
public void delete(String s)
public void refresh()
public com.ms.wfc.data.Field getItem(int n)
public com.ms.wfc.data.Field getItem(String s)

Properties

public int getCount()

Errors
Methods

public void clear()


public void refresh()
public com.ms.wfc.data.Error getItem(int n)
public com.ms.wfc.data.Error getItem(String s)

Properties

public int getCount()


See Also
Errors Collection (ADO )
Fields Collection (ADO )
Parameters Collection (ADO )
ActualSize and DefinedSize Properties Example
(VC++)
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.

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;

// Define ADO object pointers. Initialize pointers on define.


// These are in the ADODB:: namespace.
_RecordsetPtr pRstStores = NULL;

// Define Other variables


_bstr_t strMessage;
_bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated
Security='SSPI';");

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();

// GetActiveConnection returns connect string if connection


// is not open, else returns Connection object.
switch(vtConnect.vt) {
case VT_BSTR:
printf("Error:\n");
printf("Code = %08lx\n", e.Error());
printf("Message = %s\n", e.ErrorMessage());
printf("Source = %s\n", (LPCSTR) e.Source());
printf("Description = %s\n", (LPCSTR) e.Description());
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}

// Clean up objects before exit.


if (pRstStores)
if (pRstStores->State == adStateOpen)
pRstStores->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;
long nCount = 0;
long i = 0;

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);
}
}
}

Store Name: Eric the Read Books


Defined Size: 40
Actual Size: 19
Store Name: Barnum's
Defined Size: 40
Actual Size: 8
Store Name: News & Brews
Defined Size: 40
Actual Size: 12
Store Name: Doc-U -Mat: Quality Laundry and Books
Defined Size: 40
Actual Size: 36
Store Name: Fricative Bookshop
Defined Size: 40
Actual Size: 18
Store Name: Bookbeat
Defined Size: 40
Actual Size: 8

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";

_bstr_t strText("SELECT * FROM authors WHERE state = ?");


pCmd->CommandText = strText;

pPrm = pCmd->CreateParameter("ItemXparm", adChar, adParamInput, 2, "CA");


pCmd->Parameters->Append(pPrm);

pConnection->Open(strCnn, "", "", adConnectUnspecified);


pCmd->ActiveConnection = pConnection;

// Connection and CommandType are omitted because a Command object is provided.


_variant_t Conn;
Conn.vt = VT_ERROR;
Conn.scode = DISP_E_PARAMNOTFOUND;

pRst->Open((_variant_t((IDispatch *) pCmd)), Conn, adOpenStatic, adLockReadOnly, -1);

printf("The Parameters collection accessed by index...\n");

vIndex = (short) 0;
pPrm = pCmd->Parameters->GetItem(&vIndex);
printf("Parameter name = '%s', value = '%s'\n",
(LPCSTR)pPrm->Name, (LPSTR)(_bstr_t)pPrm->Value);

printf("\nThe Parameters collection accessed by name...\n");


pPrm = pCmd->Parameters->Item["ItemXparm"];
printf("Parameter name = '%s', value = '%s'\n",
(LPCSTR)pPrm->Name, (LPSTR)(_bstr_t)pPrm->Value);

printf("\nThe Fields collection accessed by index...\n");


pRst->MoveFirst();
long limit = 0;
limit = ((pRst->Fields->Count) - 1);
int intLineCnt = 8;
for (short iIndex = 0 ; iIndex <= limit ; iIndex++) {
vIndex = iIndex;

pFld = pRst->Fields->GetItem(&vIndex);
printf("Field %d : Name = '%s', ", iIndex, (LPCSTR)pFld->GetName());
_variant_t FldVal = pFld->GetValue();

// Because Value is the default property of a Property object, the use


// of the actual keyword here is optional.
switch(FldVal.vt) {
case (VT_BOOL):
if (FldVal.boolVal)
printf("Value = 'True'");
else
printf("Value = 'False'");
printf("\n");
break;
case (VT_BSTR):
printf("Value = '%s'",
(LPCSTR)(_bstr_t)FldVal.bstrVal);
printf("\n");
break;
case (VT_I4):
printf("Value = '%s'",(LPCSTR)FldVal.iVal);
printf("\n");
break;
case (VT_EMPTY):
printf("Value = '%s'",(LPCSTR)FldVal.lVal);
printf("\n");
break;
default:
break;
}
}

printf("\nThe Fields collection accessed by name...\n");


pRst->MoveFirst();

for (int iIndex = 0; iIndex <= 8 ; iIndex++) {


intLineCnt++;

pFld = pRst->Fields->GetItem(Column[iIndex]);
printf("Field name = '%s', ", (LPCSTR)pFld->GetName());
_variant_t FldVal = pFld->GetValue();

// Because Value is the default property of a Property object,


// the use of the actual keyword here is optional.
switch(FldVal.vt) {
case (VT_BOOL):
if (FldVal.boolVal)
printf("Value = 'True'");
else
printf("Value = 'False'");
printf("\n");
break;
case (VT_BSTR):
printf("Value = '%s'",
(LPCSTR)(_bstr_t)FldVal.bstrVal);
printf("\n");
break;
case (VT_I4):
printf("Value = '%s'", (LPCSTR)FldVal.iVal);
printf("\n");
break;
case (VT_EMPTY):
printf("Value = '%s'", (LPCSTR)FldVal.lVal);
printf("\n");
break;
default:
break;
}
}
}
catch(_com_error &e) {
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
PrintProviderError(pConnection);
PrintComError(e);
}

// Clean up objects before exit.


if (pRst)
if (pRst->State == adStateOpen)
pRst->Close();
if (pConnection)
if (pConnection->State == adStateOpen)
pConnection->Close();
}

void PrintProviderError(_ConnectionPtr pConnection) {


// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

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);
}
}
}
}

void PrintComError(_com_error &e) {


_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.


printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}

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

Represents a stream of binary data or text.


In tree-structured hierarchies such as a file system or an e-mail system, a Record may have a
default binary stream of bits associated with it that contains the contents of the file or the e-mail.
A Stream object can be used to manipulate fields or records containing these streams of data. A
Stream object can be obtained in these ways:
From a URL pointing to an object (typically a file) containing binary or text data. This object
can be a simple document, a Record object representing a structured document, or a folder.
By opening the default Stream object associated with a Record object. You can obtain the
default stream associated with a Record object when the Record is opened, to eliminate a
round-trip just to open the stream.
By instantiating a Stream object. These Stream objects can be used to store data for the
purposes of your application. Unlike a Stream associated with a URL, or the default
Stream of a Record, an instantiated Stream has no association with an underlying source
by default.
With the methods and properties of a Stream object, you can do the following:
Open a Stream object from a Record or URL with the Open method.
Close a Stream with the Close method.
Input bytes or text to a Stream with the Write and WriteText methods.
Read bytes from the Stream with the Read and ReadText methods.
Write any Stream data still in the ADO buffer to the underlying object with the Flush
method.
Copy the contents of a Stream to another Stream with the CopyTo method.
Control how lines are read from the source file with the SkipLinemethod and the
LineSeparator property.
Determine the end of stream position with the EOSproperty and SetEOS method.
Save and restore data in files with the SaveToFileand LoadFromFile methods.
Specify the character set used for storing the Stream with the Charset property.
Halt an asynchronous Stream operation with the Cancel method.
Determine the number of bytes in a Stream with the Size property.
Control the current position within a Stream with the Position property.
Determine the type of data in a Stream with the Type property.
Determine the current state of the Stream (closed, open, or executing) with the State
property.
Specify the access mode for the Stream with the Mode property.
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.

The Stream object is safe for scripting.


This section contains the following topics.
Stream Object Properties, Methods, and Events

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

Specifies the character used as a line separator in text Stream objects.

CONSTANT VALUE DESCRIPTION

adCR 13 Indicates carriage return.

adCRLF -1 Default. Indicates carriage return line


feed.

adLF 10 Indicates line feed.

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

Writes binary data to a Stream object.

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

Indicates the current value of a Field object in the database.

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

You might also like