BeginTrans, CommitTrans, and RollbackTrans Methods Example (VC++)
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.
// BeginBeginTransCpp
#import "C:\Program Files\Common Files\System\ADO\msado15.d
no_namespace rename("EOF", "EndOfFile")
#include <stdio.h>
#include <ole2.h>
#include <conio.h>
#include <assert.h>
#include <malloc.h>
#include "BeginTransX.h"
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void BeginTransX(void);
void PrintProviderError(_Connec
void main()
{
if(FAILED(::CoInitialize(N
return;
BeginTransX();
//Wait here for user to see the output.
printf("\nPress any key to continue...");
getch();
::CoUninitialize();
}
//////////////////////////
// //
// BeginTransX Function //
// //
//////////////////////////
void BeginTransX()
{
// Define ADO object pointers.
// Initialize pointers on define.
// These are in the ADODB:: namespace.
_RecordsetPtr rstTitles = NULL;
_ConnectionPtr pConnection = NULL;
//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;
"Initial Catalog=pubs;User Id=sa;Password=;");
TESTHR(pConnection.CreateI
TESTHR(pConnection->Open(s
rstTitles.CreateInstance(_
rstTitles->CursorType = adOpenDynamic;
rstTitles->LockType = adLockPessimistic;
// open Titles table
TESTHR(rstTitles->Open("ti
_variant_t((IDispatch*)pCo
adOpenDynamic, adLockPessimistic,adCmdTab
rstTitles->MoveFirst();
pConnection->BeginTrans();
//Open an IADORecordBinding interface pointer which
//we'll use for Binding Recordset to a class
TESTHR(rstTitles->QueryInt
__uuidof(IADORecordBinding
//Bind the Recordset to a C++ Class here
TESTHR(picRs->BindToRecord
// Loop through recordset and ask user if he wants
// to change the type for a specified title.
// Allocate memory to p_TempStr string pointer.
p_TempStr = (LPSTR) malloc(sizeof(titlrs.m_szT
// Check for null string.
assert(p_TempStr != NULL);
while (VARIANT_FALSE == rstTitles->EndOfFile)
{
// Remove blank string
strcpy(p_TempStr,strtok(ti
// Compare type with psychology
if (!strcmp(p_TempStr,"psycho
{
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)strM
do
{
chKey = getch();
}while(chKey != 'y' && chKey !='n');
if(chKey == 'y')
{
// Copy "self_help" title field
strcpy(titlrs.m_szT_type,"
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->QueryInt
__uuidof(IADORecordBinding
(LPVOID*)&picRs));
// Rebind the Recordset to a C++ Class.
TESTHR(picRs->BindToRecord
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,t
rstTitles->MoveNext();
}
// Restore original data becasue this is a demonstration.
rstTitles->MoveFirst();
while (VARIANT_FALSE == rstTitles->EndOfFile)
{
strcpy(p_TempStr,titlrs.m_
p_TempStr = strtok(p_TempStr," ");
if (!strcmp(p_TempStr,"self_h
{
strcpy(titlrs.m_szT_type,"
picRs->Update(&titlrs);
}
rstTitles->MoveNext();
}
// Deallocate the memory
free(p_TempStr);
// Clean up objects before exit.
rstTitles->Close();
pConnection->Close();
//Release IADORecordset Interface
if (picRs)
picRs->Release();
}
catch(_com_error &e)
{
// Notify the user of errors if any.
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Descript
PrintProviderError(pConnec
printf("Source : %s\n",(LPCSTR)bstrSource);
printf("Description : %s\n",(LPCSTR)bstrDescript
}
};
//////////////////////////
// //
// PrintProviderError Function //
// //
//////////////////////////
void PrintProviderError(_Connec
{
// 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->Coun
{
nCount = pConnection->Errors->Count
// Collection ranges from 0 to nCount -1.
for(i = 0; i < nCount; i++)
{
pErr = pConnection->Errors->GetIt
printf("Error number: %x\t%s\n", pErr->Number,(LPCSTR) pErr->Description);
}
}
}
// EndBeginTransCpp
BeginTransX.h:
// BeginBeginTransH
#include "icrsint.h"
//This Class extracts only title and type
class CTitlesRs : public CADORecordBinding
{
BEGIN_ADO_BINDING(CTitlesR
//Column title is the 2nd field in the recordset
ADO_VARIABLE_LENGTH_ENTRY2
sizeof(m_szT_title), lT_titleStatus, FALSE)
//Column type is the 3rd field in the recordset
ADO_VARIABLE_LENGTH_ENTRY2
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;
};
// EndBeginTransH
See Also
BeginTrans, CommitTrans, and RollbackTrans Methods | Update Method
) 1998-2001 Microsoft Corporation. All rights reserved.
Main Topics
Browse All Topics





by: peterdownesPosted on 2002-10-22 at 22:46:15ID: 7359110
BeginTrans, CommitTrans, and RollbackTrans Methods
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.
See Also
Visual Basic Example | Visual C++ Example | Visual J++ Example
Attributes Property
Applies To: Connection Object
© 1998-2001 Microsoft Corporation. All rights reserved.