DAO Data Access Object is supplied in the form of redistributable components enable you to access...

Preview:

Citation preview

DAODAO

Data Access ObjectData Access Object

is supplied in the form of is supplied in the form of redistributable components redistributable components

enable you to access and manipulate enable you to access and manipulate databases through the databases through the Microsoft Jet Microsoft Jet database engine. database engine.

Similar to ODBCSimilar to ODBC

Won’t support Won’t support Remote Remote CommunicationCommunication

Is based on OLE.Is based on OLE.

DAO ClassesDAO Classes

DAO ClassesDAO Classes Cont…Cont…

CDaoRecordsetCDaoRecordset Just like CRecordset Object in ODBCJust like CRecordset Object in ODBC

NavigationNavigation functions include functions include Find, FindFirst, FindLast, FindNext, and Find, FindFirst, FindLast, FindNext, and FindPrev FindPrev

Move, MoveFirst, MoveLast, MoveNext, and Move, MoveFirst, MoveLast, MoveNext, and MovePrev. MovePrev.

Data updateData update functions include functions includeAddNew,AddNew,

CancelUpdate,CancelUpdate,

Delete, Delete,

Edit, and Update.Edit, and Update.

DAO ClassesDAO Classes Cont…Cont…

CDaoDatabaseCDaoDatabase

represents a connection to a represents a connection to a databasedatabase

Connection creation - Connection creation - CDaoDatabase::OpenCDaoDatabase::Open

Termination - Termination - CDaoDatabase::CloseCDaoDatabase::Close

New database creation - New database creation - CDaoDatabase::CreateCDaoDatabase::Create

Deletes a DAO TableDef object and also the Deletes a DAO TableDef object and also the underlying table and all its data from the underlying table and all its data from the database. - database. - DeleteTableDef ()DeleteTableDef ()

DAO ClassesDAO Classes Cont…Cont…

CDaoWorkspaceCDaoWorkspace

represents database sessionsrepresents database sessions Creation of workspace - Creation of workspace - CDaoWorkspace::CreateCDaoWorkspace::Create

Opening an existing workspace - Opening an existing workspace - CDaoWorkspace::OpenCDaoWorkspace::Open

CDaoQueryDefCDaoQueryDef represents query definitionsrepresents query definitions

To create a new query - To create a new query - CQueryDef::Create CQueryDef::Create

to access a existing query - to access a existing query - CQueryDef::OpenCQueryDef::Open

to execute a query - to execute a query - CQueryDef::ExecuteCQueryDef::Execute

DAO ClassesDAO Classes Cont…Cont…

CDaoTableDefCDaoTableDef represents table definitions represents table definitions

open an existing table in a database - open an existing table in a database - CDaoTableDef::Open CDaoTableDef::Open

Creation of new table - Creation of new table - DaoTableDef::CreateDaoTableDef::Create

Fields can be created and deleted by Fields can be created and deleted by calling calling

CreateFieldCreateField and and

DeleteFieldDeleteField member functions member functions

CDaoFieldExchange CDaoFieldExchange DaoRecordset::DoFieldExchangeDaoRecordset::DoFieldExchange

ODBC Vs DAOODBC Vs DAO

DAODAO - When you only need access to - When you only need access to data in a format that the Microsoft Jet data in a format that the Microsoft Jet engine can read directly (engine can read directly (Access Access formatformat, , Excel formatExcel format, and so on) , and so on)

ODBCODBC – In more complex cases when – In more complex cases when your data exists on a server or on a your data exists on a server or on a variety of different servers . variety of different servers .

Example 1Example 1

Create a Visual C++ application using Create a Visual C++ application using Appwizard to connect the Access database Appwizard to connect the Access database and display the records. and display the records.

DEMO1

Example 2Example 2Create a Visual C++ application using Appwizard Create a Visual C++ application using Appwizard to connect the Access database and perform to connect the Access database and perform Navigation and Manipulation operation using Navigation and Manipulation operation using Dialog Controls.Dialog Controls.

DEMO2

Network IssuesNetwork Issues

Network protocols - Network protocols - LayeringLayering

Internet ProtocolInternet ProtocolVersion

(4)

Destination IP Address (32)

Options (0 or 32 if any)

Data (varies if any)

1Bit 0 Bit 15 Bit 16 Bit 31

HeaderLength (4)

Priority & Type of Service (8) Total Length (16)

Flags(3) Fragment offset (13)

Time to live (8) Protocol (8) Header checksum (16)

Source IP Address (32)

20Bytes

Connection-oriented protocol - Connection-oriented protocol - TCPTCP

Source port (16) Destination port (16)

Sequence number (32)

Headerlength (4)

Acknowledgement number (32)

Reserved (6) Window (16)

Checksum (16)

Options (0 or 32 if any)

Data (varies)

20Bytes

Bit 0 Bit 15 Bit 16 Bit 31

Connectionless -UDPConnectionless -UDP

Source port (16) Destination port (16)

Length (16)

Data (if any)

1Bit 0 Bit 15 Bit 16 Bit 31

Checksum (16)

8Bytes

IP AddressIP Address

1

Class A:

Bits:0NNNNNNN0NNNNNNN HostHost HostHost HostHost

8 9 16 17 24 25 32

Range (1-126)

1

Class B:

Bits:10NNNNNN10NNNNNN NetworkNetwork HostHost HostHost

8 9 16 17 24 25 32

Range (128-191)1

Class C:

Bits:110NNNNN110NNNNN NetworkNetwork NetworkNetwork HostHost

8 9 16 17 24 25 32

Range (192-223)1

Class D:

Bits:1110MMMM1110MMMM Multicast GroupMulticast Group Multicast GroupMulticast Group Multicast GroupMulticast Group

8 9 16 17 2425 32

Range (224-239)

Network Byte Order

All values stored in a sockaddr_in must be in network byte order.sin_port a TCP/IP port number.

sin_addr an IP address.

Network Byte Order Network Byte Order functionsfunctions

‘‘hh’ : host byte order ‘’ : host byte order ‘nn’ : network ’ : network byte orderbyte order

‘‘ss’ : short (16bit) ‘’ : short (16bit) ‘ll’ : long (32bit)’ : long (32bit)

uint16_t htons(uint16_t);uint16_t htons(uint16_t);

uint16_t ntohs(uint_16_t);uint16_t ntohs(uint_16_t);

uint32_t htonl(uint32_t);uint32_t htonl(uint32_t);

uint32_t ntohl(uint32_t);uint32_t ntohl(uint32_t);

File System –NTFS Vs FATFile System –NTFS Vs FAT

NTFS FAT

More secured Less Secured

User permission for individual files and folders

No individual user permissions

Used with Win 95,98 Used with Win NT and above

SocketSocket

A socket is an abstract A socket is an abstract representation of a communication representation of a communication endpoint.endpoint.

Sockets work with Unix I/O services Sockets work with Unix I/O services just like files, pipes & FIFOs.just like files, pipes & FIFOs.

Sockets have special needs:Sockets have special needs:establishing a connectionestablishing a connection

specifying communication endpoint specifying communication endpoint addressesaddresses

SocketsSockets

Figure A

Figure B

WinsockWinsock

If the client and the server use the same protocol suite (TCP/IP), then they can

communicate even if they use different application program interfaces.

WinSock is an interface but it is not a protocol. It is the lowest level Window API.

Part code located in wsock32.dll and part inside windows kernel.

3 Types of Socket3 Types of Socket

Stream sockets interface to the Stream sockets interface to the TCP (transmission control TCP (transmission control protocol).protocol).

Datagram sockets interface to the Datagram sockets interface to the UDP (user datagram protocol).UDP (user datagram protocol).

Raw sockets interface to the IP Raw sockets interface to the IP (Internet protocol).(Internet protocol).

MFC Winsock classesMFC Winsock classes

CAsyncSocket - CAsyncSocket is a thin wrapper CAsyncSocket - CAsyncSocket is a thin wrapper around the C APIaround the C API

CSocket – base classCSocket – base class

CBlockingSocket - A thin wrapper around the CBlockingSocket - A thin wrapper around the Windows API.Windows API.

Feature :Exception throwing and time outs Feature :Exception throwing and time outs

CHttpBlockingSocket –read http dataCHttpBlockingSocket –read http data

Helper classes:CSockAddr & Helper classes:CSockAddr & CBlockingSocketExceptionCBlockingSocketException

CSockAddrCSockAddr

struct sockaddr {uint8_t sa_len;

sa_family_t sa_family; char sa_data[14];

};

sa_family specifies the address type. sa_data specifies the address value.

Used b

y ke

rnel

CSockAddrCSockAddr

struct sockaddr_in {struct sockaddr_in {

uint8_tuint8_t sin_len;sin_len;

sa_family_tsa_family_t sin_family;sin_family;

in_port_tin_port_t sin_port;sin_port;

struct in_addrstruct in_addr sin_addr; sin_addr;

charchar sin_zero[8];sin_zero[8];

};};

A special kind of sockaddr structureA special kind of sockaddr structure

sockaddrsockaddr

sa_lensa_len

sa_familysa_family

sa_datasa_data

Sockaddr_inSockaddr_in

sin_lensin_len

AF_INETAF_INET

Sin_zeroSin_zero

sin_portsin_port

Sin_addrSin_addr

Windows API: ServerWindows API: Server

socket()

bind()

listen()

accept()

read()

write()

close()

Create initial data structures

Attach to an interface

Begin listening for a connection

Accept the next connection

Read & write data, close down

Done in ServerSocketConstructor

In Java

Windows API: ClientWindows API: Client

socket

connect

Send/receive

Close/cleanup

Create data structures

Connect to the server

Class definitionClass definitionclass CSockAddr : public sockaddr_in {class CSockAddr : public sockaddr_in {public: public: // constructors // constructors CSockAddr() CSockAddr()

{ { sin_family = AF_INET; sin_family = AF_INET;

sin_port = 0; sin_port = 0; sin_addr.s_addr = 0; } // Default sin_addr.s_addr = 0; } // Default

CSockAddr(const SOCKADDR& sa) { memcpy(this, &sa, CSockAddr(const SOCKADDR& sa) { memcpy(this, &sa, sizeof(SOCKADDR)); } sizeof(SOCKADDR)); }

CSockAddr(const SOCKADDR_IN& sin) { memcpy(this, &sin, CSockAddr(const SOCKADDR_IN& sin) { memcpy(this, &sin, sizeof(SOCKADDR_IN)); } sizeof(SOCKADDR_IN)); }

CSockAddr(const ULONG ulAddr, const USHORT ushPort = 0) CSockAddr(const ULONG ulAddr, const USHORT ushPort = 0) // parms are host byte ordered // parms are host byte ordered { { sin_family = AF_INET; sin_family = AF_INET; sin_port = htons(ushPort); sin_port = htons(ushPort); sin_addr.s_addr = htonl(ulAddr); sin_addr.s_addr = htonl(ulAddr); } } CSockAddr(const char* pchIP, const USHORT ushPort = 0) CSockAddr(const char* pchIP, const USHORT ushPort = 0) // dotted IP addr string // dotted IP addr string { { sin_family = AF_INET; sin_family = AF_INET; sin_port = htons(ushPort); sin_port = htons(ushPort); sin_addr.s_addr = inet_addr(pchIP); sin_addr.s_addr = inet_addr(pchIP); } // already network byte ordered } // already network byte ordered

WinInetWinInet

WinInet is a higher-level API ,but it works WinInet is a higher-level API ,but it works only for HTTP, FTP, and gopher client only for HTTP, FTP, and gopher client programs programs

BenefitsBenefits

CachingCaching

SecuritySecurity

Web proxy accessWeb proxy access

User friendlyUser friendly

MFC WinInet ClassesMFC WinInet Classes

CInternetSessionCInternetSession

CHttpConnectionCHttpConnection

CFtpConnectionCFtpConnection

CGopherConnectionCGopherConnection

MonikerMoniker

A moniker is a COM object that holds A moniker is a COM object that holds the name (URL) of the object, which the name (URL) of the object, which could be an embedded component could be an embedded component but more often is just an Internet file. but more often is just an Internet file.

Monikers implement the Monikers implement the IMonikerIMoniker interface, which has two important interface, which has two important member functions: member functions: BindToObject - BindToObject - object into running stateobject into running state

BindToStorage - object data can be BindToStorage - object data can be readread

Internet Information ServerInternet Information Server

IISIIS

3 servers3 servers

High performance Internet/Intranet serverHigh performance Internet/Intranet server

Special kind of Windows program- serviceSpecial kind of Windows program- service

Allows to define virtual web serverAllows to define virtual web server

Provides for Strong AuthenticationProvides for Strong Authentication

Allows IP source filteringAllows IP source filtering

Scaled down –Personal Web ServerScaled down –Personal Web Server

ISAPIISAPI

An ISAPI server extension can perform An ISAPI server extension can perform Internet business transactions such as Internet business transactions such as order entry. It is a program runs in order entry. It is a program runs in response to a GET or POST request from a response to a GET or POST request from a client program client program

An ISAPI filter intercepts data traveling to An ISAPI filter intercepts data traveling to and from the server and thus can perform and from the server and thus can perform specialized logging and other tasks specialized logging and other tasks

ISAPI server extension and ISAPI filter are ISAPI server extension and ISAPI filter are DLLs.DLLs.

ISAPIISAPI

ISAPI DLLs are usually stored in a ISAPI DLLs are usually stored in a separate virtual directory on the separate virtual directory on the server.server.

These DLLs must have execute These DLLs must have execute permission but do not need read permission but do not need read permission. permission.

HTTP.SYSHTTP.SYS

Called by TCP/IP when data arrives on Called by TCP/IP when data arrives on a port associated with IISa port associated with IIS

Reads HTTP headers into Kernel Reads HTTP headers into Kernel memorymemory

Maps port+hostname+application to Maps port+hostname+application to a running processa running process

Passes request to that processPasses request to that process

ISAPIISAPI

Kernel

HTTP.SYS

ApplicationProcess

some.dll

Web Service Internet

Disk Drive

web services

• CGI programs allow dynamic webpage content; HTML is built when a page is requested, instead of existing statically on disk.

• Simple uses would be hit-counters, real-time server reports, generating e-mail from web-based forms, etc.

• Compiled program executes quickly, and code can be kept elsewhere.

CompiledProgram usingThe Common

Gateway Interface(CGI)

Web Service Internet

Disk Drive

web services

Programs saved as .DLL files

• Web service recognized hits to particular file types as requests for ISAPI-generated data.

•Used in MS’s web-based server administration system.

CompiledProgram using

Internet ServicesApplication

Program Interface(ISAPI; sometimes

called ISAPI filters)

Web ServiceInternet

Disk Drive

Compiled programor

ISAPI filter

DatabaseService

•Scripts are typically run in the context of the web service user (usually an

anonymous account)

•Database services usually maintain their own

accounts and security permissions (with some

really open defaults)

•Communication between the script and the DB must

use a DB account

Database Management Database Management withwith

Visual C++ Visual C++

Presentation OutlinePresentation Outline

IntroductionIntroductionDatabase with VC++Database with VC++ODBC ArchitectureODBC ArchitectureMFC Classes Supported for ODBCMFC Classes Supported for ODBCODBC Classes OverviewODBC Classes OverviewDAO ArchitectureDAO ArchitectureDAO classes OverviewDAO classes OverviewDAO Vs ODBCDAO Vs ODBCExample 1Example 1Example 2Example 2

IntroductionIntroduction

Database is used to store data andDatabase is used to store data and

Provide access to manipulate the Provide access to manipulate the data.data.

Use of standard file formatsUse of standard file formats

Provides multiple user interactionProvides multiple user interaction

Database with Visual Database with Visual C++C++

In VC++ the database connectivity is In VC++ the database connectivity is implemented by usingimplemented by using

Open DataBase Connectivity (ODBC)Open DataBase Connectivity (ODBC)

DataAccessObject (DAO)DataAccessObject (DAO)

Active Data Object (ADO)Active Data Object (ADO)

OLE DBOLE DB

Application

Database Architecture of Database Architecture of VC++VC++

ODBC / Database Specific Driver

DAO / Microsoft Jet Engine

MFC Database Classes

Database Manager

Database

Table1Index Query

Form

ODBC ArchitectureODBC Architecture

use the ODBC API to access data from a use the ODBC API to access data from a variety of different data sourcesvariety of different data sources

Contains Driver Manager for Contains Driver Manager for performing the database activities.performing the database activities.

Supports various database drivers Supports various database drivers Microsoft SQL Server Microsoft SQL Server

Oracle Oracle

Microsoft Access Microsoft Access

Microsoft FoxPro Microsoft FoxPro

Implemented by C native APIImplemented by C native API

MFC classes for ODBCMFC classes for ODBCThere are 3 different Built in classes There are 3 different Built in classes provided by MFC provided by MFC

CDatabaseCDatabaseManages a Connection to a data source.Manages a Connection to a data source.

Work as a Database ManagerWork as a Database Manager

CRecordSetCRecordSetManages a set of rows returned from the database.Manages a set of rows returned from the database.

CRecordViewCRecordViewSimplifies the display of data from CRecordSet Object.Simplifies the display of data from CRecordSet Object.

ODBC classes overview ODBC classes overview CRecordSetCRecordSet

MFC Appwizard generates a CRecordSet derived class MFC Appwizard generates a CRecordSet derived class and return a pointer named m_pSet to our application and return a pointer named m_pSet to our application program.program.

How to Map database values to How to Map database values to RecordsetRecordset

Using Record Field ExchangeUsing Record Field Exchangewe can move the data back and forth from recordset we can move the data back and forth from recordset to data base.to data base.

The exchange is set up by implementing the The exchange is set up by implementing the CRecordset::CRecordset:: DoFieldExchange()DoFieldExchange() function, and it maps function, and it maps the member variables of Recordset and Database.the member variables of Recordset and Database.

void CChap21Set::DoFieldExchange(CFieldExchange* pFX)void CChap21Set::DoFieldExchange(CFieldExchange* pFX)

{ //{{AFX_FIELD_MAP(CChap21Set) { //{{AFX_FIELD_MAP(CChap21Set)

pFX->SetFieldType(CFieldExchange:: outputColumn); pFX->SetFieldType(CFieldExchange:: outputColumn); RFX_Long(pFX, _T("[EmpId]"), m_EmpId); RFX_Long(pFX, _T("[EmpId]"), m_EmpId);

RFX_Text(pFX, _T("[EmpName]"), m_EmpName); RFX_Text(pFX, _T("[EmpName]"), m_EmpName);

RFX_Text(pFX, _T("[Salary]"), m_Salary);RFX_Text(pFX, _T("[Salary]"), m_Salary);

//}}AFX_FIELD_MAP} //}}AFX_FIELD_MAP}

CRecordset CRecordset Cont…Cont…

CRecordset::GetFieldValue()CRecordset::GetFieldValue()Is a alternative for RecordFieldExchangeIs a alternative for RecordFieldExchange

Which enables you to retrieve the value of Which enables you to retrieve the value of any field in a current View.any field in a current View.

Even if we not defined member variable OR Even if we not defined member variable OR set up of RFX.set up of RFX.

Using the column name or index to retrieve Using the column name or index to retrieve the data the data

retrieve values as a CString or a CDBVariant retrieve values as a CString or a CDBVariant objectobject

CRecordset functionsCRecordset functions

Provides various built in functions Provides various built in functions

Table and ODBC relatedTable and ODBC related

To Navigating data in the recordsetTo Navigating data in the recordset

To Manipulating the data's in record To Manipulating the data's in record setset

Bookmark the records in a Bookmark the records in a recordsetrecordset

CRecordset CRecordset Cont…Cont…Tabl and ODBC related FunctionsTabl and ODBC related Functions

CRecordSet:: CRecordSet:: GetSQL()GetSQL()Returns the Entire SQL String.Returns the Entire SQL String.

GetTableName()GetTableName()Returns the table name used.Returns the table name used.

GetODBCFieldCount()GetODBCFieldCount()Returns the total no of columns returned by the Returns the total no of columns returned by the queryquery

Close()Close()Close the database connectionClose the database connection

Open()Open()Reconnect / connect the data base to the programReconnect / connect the data base to the program

CRecordset CRecordset Cont…Cont…

Navigating the data in recordsetNavigating the data in recordsetMoveNext()MoveNext()

MovePrev()MovePrev()

MoveLast()MoveLast()

MoveFirst()MoveFirst()

CanScroll()CanScroll()Check the recordset having only forward only Check the recordset having only forward only cursorcursor

SetAbsolutePosition()SetAbsolutePosition()Move to specific rows in Record setMove to specific rows in Record set

Which takes Zero based index into the record set. Which takes Zero based index into the record set.

CRecordset CRecordset Cont…Cont…To Manipulating the data's in record To Manipulating the data's in record

setset

Delete()Delete()Delete the current row & set the member variables Delete the current row & set the member variables NULLNULL

AddNew()AddNew()Create a new row with field values are empty.Create a new row with field values are empty.

CanAppend()CanAppend()Used to check whether record set provides adding Used to check whether record set provides adding of recordsof records

Edit()Edit()To edit or modify the current record detailsTo edit or modify the current record details

Update()Update()Used to update the record set when a new record Used to update the record set when a new record is added / existing record is edited.is added / existing record is edited.

Recordset selectionRecordset selectionVisual C++ provides 3 types of RecordsetVisual C++ provides 3 types of Recordset

They are differ in speed versus featuresThey are differ in speed versus featuresSnapshotSnapshot

DynasetDynaset

TableTable

Recordset Selection Recordset Selection Cont…Cont…

SnapshotSnapshotDownload the entire query in one shotDownload the entire query in one shotHave data as a static copyHave data as a static copyWhen any changes made to the When any changes made to the database will not reflected to the current database will not reflected to the current Application.Application.Occupy more memory to hold the data.Occupy more memory to hold the data.

DynasetDynasetOnly the records you actually need to fill Only the records you actually need to fill the screen will get downloaded.the screen will get downloaded.Take less time to reflect.Take less time to reflect.Constantly resynchronizes the recordset, Constantly resynchronizes the recordset, so that any changes will reflected so that any changes will reflected immediately.immediately.

Recordset Selection Recordset Selection Cont…Cont…

The snapshot and Dynaset work at The snapshot and Dynaset work at the record level. ODBC will only the record level. ODBC will only support this two options.support this two options.

TableTableWork with table level and supported by Work with table level and supported by DAO.DAO.

Places the contents of the query into Places the contents of the query into Temporary table.Temporary table.

Have a problem with updation.Have a problem with updation.

CRecordViewCRecordView

is basically a form view is basically a form view

make it easier to display data from a make it easier to display data from a recordset recordset

enables you to use dialog data enables you to use dialog data exchange to display data directly in a exchange to display data directly in a dialog box from the recordset dialog box from the recordset

CRecordViewCRecordView Cont…Cont…Functions of CRecordView classFunctions of CRecordView class

DoDataExchange()DoDataExchange()Perform dialog data exchange.Perform dialog data exchange.In a Normal version move data between In a Normal version move data between control and member variable.control and member variable.It will move data between the view controls It will move data between the view controls and column data member variables of and column data member variables of CRecordset.CRecordset.Sample code:Sample code:

void CChap21View::DoDataExchange(CDataExchange* void CChap21View::DoDataExchange(CDataExchange* pDX)pDX) { { CRecordView::DoDataExchange(pDX); CRecordView::DoDataExchange(pDX);

//{{AFX_DATA_MAP(CChap21View)//{{AFX_DATA_MAP(CChap21View) DDX_FieldText(pDX, IDC_DEPTCODE, m_pSet->m_Dept, DDX_FieldText(pDX, IDC_DEPTCODE, m_pSet->m_Dept,

m_pSet); DDV_MaxChars(pDX, m_pSet->m_Dept, 10); m_pSet); DDV_MaxChars(pDX, m_pSet->m_Dept, 10); DDV_MaxChars(pDX, m_pSet->m_EmpName, 50); DDV_MaxChars(pDX, m_pSet->m_EmpName, 50);

//}}AFX_DATA_MAP//}}AFX_DATA_MAP

CRecordViewCRecordView Cont…Cont…

OnGetRecordSet()OnGetRecordSet()Retrieve a pointer of the CRecordset.Retrieve a pointer of the CRecordset.

The default implementation supplied by The default implementation supplied by Class Wizard returns the pointer stored in Class Wizard returns the pointer stored in CRecordView ::m_pSet CRecordView ::m_pSet

OnMove()OnMove() takes only one parameter, specifying where takes only one parameter, specifying where to move. This can be one of the following to move. This can be one of the following constants:constants:

ID_RECORD_FIRST ID_RECORD_FIRST

ID_RECORD_LAST ID_RECORD_LAST

ID_RECORD_NEXT ID_RECORD_NEXT

ID_RECORD_PREV ID_RECORD_PREV

CDatabaseCDatabase

is used to encapsulate your is used to encapsulate your application's dealings with a application's dealings with a connection to the database connection to the database Perform ODBC C API connection Perform ODBC C API connection Handles.Handles.We can retrieve We can retrieve CDatabase CDatabase object object associated with associated with CRecordsetCRecordset by by

m_pSetm_pSet->->m_pDatabasem_pDatabase variable in variable in CRecordsetCRecordset

Used to execute SQL statementsUsed to execute SQL statements void ExecuteSQL(LPCSTR sqlstmt)void ExecuteSQL(LPCSTR sqlstmt)

Takes SQL String & execute it against the Takes SQL String & execute it against the current datasourcecurrent datasourceDoes not return error, if any run time error Does not return error, if any run time error occurs, occurs, CDBExceptionCDBException will be thrown will be thrown

CDatabaseCDatabaseCont…Cont…Transaction with CDatabaseTransaction with CDatabase

Enables to execute a series of SQL Enables to execute a series of SQL statements as a single operation.statements as a single operation.One of the operation fails, rest of all can be One of the operation fails, rest of all can be undone.undone.This is most useful future for doing related This is most useful future for doing related updation to various tables at the same time.updation to various tables at the same time.

CanTransact()CanTransact()BeginTrans()BeginTrans()

Tells transaction process starts.Tells transaction process starts.

ExecuteSQL()ExecuteSQL()CommitTrans()CommitTrans()Rollback()Rollback()The functions work properly, depends on The functions work properly, depends on the ODBC driver support.the ODBC driver support.

CDatabaseCDatabase Cont…Cont…

This example shows a simple This example shows a simple transaction involving a row insertion transaction involving a row insertion made by calling ExecuteSQL(): made by calling ExecuteSQL():

try { try {

m_pSet->m_pDatabase->BeginTrans();m_pSet->m_pDatabase->BeginTrans();

m_pSet->m_pDatabase->ExecuteSQL( "INSERT INTO m_pSet->m_pDatabase->ExecuteSQL( "INSERT INTO Employee VALUES ('Joe Beancounter', 'Accounting', 80000)");Employee VALUES ('Joe Beancounter', 'Accounting', 80000)");

m_pSet->m_pDatabase->CommitTrans();m_pSet->m_pDatabase->CommitTrans();

}}

catch(CDBException *pEx)catch(CDBException *pEx)

{{

pEx->ReportError();pEx->ReportError();

m_pSet->m_pDatabase->Rollback();m_pSet->m_pDatabase->Rollback();

} }

Recommended