Click here to Skip to main content
15,867,308 members
Articles / Desktop Programming / MFC
Article

A set of ODBC Classes

Rate me:
Please Sign up or sign in to vote.
4.90/5 (24 votes)
27 Aug 20015 min read 491.2K   3.2K   75   78
Two classes that make easy to work with ODBC

Overview

I created this classes to make it easy to work with ODBC. For this I created the CODBCDatabase and CODBCRecordset classes

The CODBCDatabase Class

CODBCDatabase::CODBCDatabase

Constructs a CODBCDatabase object.

CODBCDatabase();

See sample

CODBCDatabase::Open

The Open establishes connections to a driver and a data source.

BOOL Open(CHAR* lpstrDSN, CHAR* lpstrUser = NULL, CHAR* lpstrPass = NULL);

Parameters

CHAR* lpstrDSN Pointer to a null-terminated string containing the data source name

CHAR* lpstrUser = NULL Pointer to a null-terminated string containing the user identifier

CHAR* lpstrPass = NULL Pointer to a null-terminated string containing the authentication string (typically the password).

If the function succeeds, this returns TRUE.

See sample

CODBCDatabase::DriverConnect

DriverConnect supports data sources that require more connection information than the three arguments in Open function, dialog boxes to prompt the user for all connection information, and data sources that are not defined in the system information.

BOOL DriverConnect(CHAR* szConnStr, CHAR* szConnStrOut = NULL, HWND hWnd = NULL, enum drvCompletion drvConn = sqlNoPrompt);

Parameters

CHAR* szConnStrPointer to a null-terminated string containing a full connection string (see the syntax in "Comments"), a partial connection string, or an empty string.

CHAR* szConnStrOut = NULL Pointer to a buffer for the completed connection string.

HWND hWnd = NULL Window handle. The application can pass the handle of the parent window, if applicable, or a null pointer if either the window handle is not applicable or DriverConnect will not present any dialog boxes.

enum drvCompletion drvConn Flag that indicates whether the Driver Manager or driver must prompt for more connection information:

    CODBCDatabase::sqlNoPrompt

    CODBCDatabase::sqlPrompt

If the function succeeds, this returns TRUE.

See sample

CODBCDatabase::SetReadOnly

The SetReadOnly indicator that the connection is not required to support SQL statements that cause updates to occur.

void SetReadOnly(BOOL bReadOnly = TRUE);

Parameters

BOOL bReadOnly = TRUE Set read only

If the function succeeds, this returns TRUE.

CODBCDatabase::SetLoginTimeout

The SetLoginTimeout set the number of seconds to wait for a login request to complete before returning to the application.

void SetLoginTimeout(LONG nSeconds);

Parameters

LONG nSeconds The time in seconds. If it is 0, the timeout is disabled and a connection attempt will wait indefinitely.

CODBCDatabase::SetConnectionTimeout

The SetConnectionTimeout set the number of seconds to wait for any request on the connection to complete before returning to the application.

void SetConnectionTimeout(LONG nSeconds);

Parameters

LONG nSeconds The time in seconds

See sample

CODBCDatabase::GetConnectionTimeout

The GetConnectionTimeout returns the time n seconds of connection timeout.

LONG GetConnectionTimeout();

CODBCDatabase::Execute

The Execute function executes a SQL preparable statement.

BOOL Execute(CHAR* szSqlStr);

Parameters

CHAR* szSqlStr</p> Pointer to a null-terminated string containing the SQL statement to be executed

If the function succeeds, this returns TRUE.

See sample

<A name=Sample0>
CODBCDatabase pdb;

if(!pdb.DriverConnect("DSN=Test;SERVER=ServerSQL;UID=;PWD=;DATABASE=TestDatabase;"))
  return FALSE;

pdb.Execute("Delete Test Where Field1 >= 17");
n = pdb.GetRowsAffected();
</A>

CODBCDatabase::GetRowsAffected

The GetRowsAffected returns the number of rows affected for the last Execute.

int GetRowsAffected();

See sample

CODBCDatabase::IsConnected

The IsConnected returns true if the connection to database is open.

BOOL IsConnected();

CODBCDatabase::Close

The Close function closes the connection.

void Close();

See sample

The CODBCRecordset Class

CODBCRecordset::CODBCRecordset

Constructs a CODBCRecordset object.

CODBCRecordset(CODBCDatabase* pDb);

Parameters

CODBCDatabase* pDb Pointer to the CODBCDatabase Object.

See sample

CODBCRecordset::Open

The Open executes a preparable SQL statement.

BOOL Open(CHAR* szSqlStr);

Parameters

CHAR* szSqlStr Pointer to a null-terminated string containing a SQL statement.

See sample

CODBCRecordset::GetFieldLength

The GetFieldLength returns the size of the Field on the data source.

LONG GetFieldLength(int nField);

Parameters

int nField Field Index of result data, ordered sequentially in increasing Field order, starting at 0

CODBCRecordset::GetFieldIndex

The GetFieldIndex returns the index of a specific field name. If the field name don't exist GetFieldIndex returns -1.

int GetFieldIndex(CHAR* szFieldName);

Parameters

CHAR* szFieldName Pointer to a null-terminated string containing the Field Name.

CODBCRecordset::GetFieldName

The GetFieldName returns the field name in the result set.

BOOL GetFieldName(int nField, CHAR* szFieldName);

Parameters

int nField

CHAR* szFieldName Pointer to a buffer in which to return the Field Name.

CODBCRecordset::GetFieldAttributes

The GetFieldAttributes returns the result descriptor—field name, type, field size-for one column in the result set.

BOOL GetFieldAttributes(int nField, CHAR* szFieldName, int& nType, int& nLength);

Parameters

int nField Field Index of result data, ordered sequentially in increasing Field order, starting at 0

CHAR* szFieldName Pointer to a buffer in which to return the Field Name.

int& nType Pointer to a buffer in which to return the SQL Data Type of the Field.

int& nLength Pointer to a buffer in which to return the size of the Field on the data source.

See sample

Data Types

    CODBCRecordset::typeChar

    CODBCRecordset::typeVarChar

    CODBCRecordset::typeLongVarChar

    CODBCRecordset::typeWChar

    CODBCRecordset::typeWVarChar

    CODBCRecordset::typeWLongVarChar

    CODBCRecordset::typeDecimal

    CODBCRecordset::typeNumeric

    CODBCRecordset::typeSmallint

    CODBCRecordset::typeInteger

    CODBCRecordset::typeReal

    CODBCRecordset::typeFloat

    CODBCRecordset::typeDouble

    CODBCRecordset::typeBit

    CODBCRecordset::typeTinyint

    CODBCRecordset::typeBigInt

    CODBCRecordset::typeBinary

    CODBCRecordset::typeVarBinary

    CODBCRecordset::typeLongVarBinary

    CODBCRecordset::typeDate

    CODBCRecordset::typeTime

    CODBCRecordset::typeTimeStamp

    CODBCRecordset::typeIntervalMonth

    CODBCRecordset::typeIntervalYear

    CODBCRecordset::typeIntervalYearToMonth

    CODBCRecordset::typeIntervalDay

    CODBCRecordset::typeIntervalHour

    CODBCRecordset::typeIntervalMinute

    CODBCRecordset::typeIntervalSecond

    CODBCRecordset::typeIntervalDayToHour

    CODBCRecordset::typeIntervalDayToMinute

    CODBCRecordset::typeIntervalDayToSecond

    CODBCRecordset::typeIntervalHourToMinute

    CODBCRecordset::typeIntervalHourToSecond

    CODBCRecordset::typeIntervalMinuteToSecond

    CODBCRecordset::typeGUID

CODBCRecordset::GetFieldCount

The GetFieldCount returns the number of fields in the result set.

int GetFieldCount();

CODBCRecordset::GetFieldValue

The GetFieldValue.

BOOL GetFieldValue(int nField, CHAR* szData);
BOOL GetFieldValue(CHAR* szFieldName, CHAR *szData);
BOOL GetFieldValue(int nField, LONG *lData);
BOOL GetFieldValue(CHAR* szFieldName, LONG *lData);
BOOL GetFieldValue(int nField, DOUBLE *dblData);
BOOL GetFieldValue(CHAR* szFieldName, DOUBLE *dblData);	
BOOL GetFieldValue(int nField, struct tm* time);
BOOL GetFieldValue(CHAR* szFieldName, struct tm* time);

Parameters

int nField Field Index of result data, ordered sequentially in increasing Field order, starting at 0

CHAR* szFieldName Pointer to a null-terminated string containing the Field Name

CHAR* szData Pointer to the buffer in which to return the data.

LONG *lData Pointer to a null-terminated string buffer in which to return the data.

DOUBLE *dblData Pointer to a double buffer in which to return the data.

struct tm* time Pointer to a time struct buffer in which to return the data

If the function succeeds, this returns TRUE.

See sample

CODBCRecordset::MoveFirst

The MoveFirst makes the First record of the recordset the current record.

BOOL MoveFirst();

If the function succeeds, this returns TRUE.

CODBCRecordset::MoveNext

The MoveNext makes the Next record of the recordset the current record.

BOOL MoveNext();

If the function succeeds, this returns TRUE.

See sample

CODBCRecordset::MovePrevious

The MovePrevious makes the Previous record of the recordset the current record.

BOOL MovePrevious();

If the function succeeds, this returns TRUE.

CODBCRecordset::MoveLast

The MoveLast makes the Last record of the recordset the current record.

BOOL MoveLast();

If the function succeeds, this returns TRUE.

CODBCRecordset::IsEof

The IsEof returns true if the current position contains no records.

BOOL IsEof();

If the function succeeds, this returns TRUE.

See sample

CODBCRecordset::IsBof

The IsBof returns true if the current position is the bottom of the recordset.

BOOL IsBof();

If the function succeeds, this returns TRUE.

CODBCRecordset::Close

The Close.

void Close();

See sample

Sample:

<A name=TheSample>
	CODBCDatabase pdb;

	pdb.SetConnectionTimeout(15);
	if(!pdb.DriverConnect("DSN=Test;SERVER=ServerSQL;UID=;PWD=;DATABASE=TestDatabase;"))
	  return FALSE;
	  
	CODBCRecordset prs = CODBCRecordset(&pdb);
	prs.Open("Select * From test");

	char szData[256];
	
	while(!prs.IsEof())
	{
		int nType;
		long lData;
		double dblData;
		int nLen;
		struct tm time;

		prs.GetFieldAttributes(0, NULL, nType, nLen);

		switch(nType)
		{
			case CODBCRecordset::typeChar:
			case CODBCRecordset::typeVarChar:
			memset(szData, 0, sizeof(szData));
			prs.GetFieldValue(0, szData);
			break;
		}

		prs.GetFieldValue(1, &lData);

		memset(szData, 0, sizeof(szData));
		prs.GetFieldValue(2, szData);

		prs.GetFieldValue(3, &time);

		memset(szData, 0, sizeof(szData));
		prs.GetFieldValue(4, szData);

		dblData = 0;
		prs.GetFieldValue(5, &dblData);
		
		dblData = 0;
		prs.GetFieldValue(6, &dblData);

		prs.MoveNext();
	}
	prs.Close();
	pdb.Close();
</A>

Carlos A. Antollini.

Updates

14 August 2001    Version 1.0 Released.

29 August 2001    Updated source files.

Special thanks

The CODBC* class have received many suggestions from the readers. Thank to All for your colaboration.


License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect Citigroup
Argentina Argentina
Carlos Antollini is a software engineer working on Object Oriented, Visual C++, MFC, COM, ATL, ADO, Internet technologies and Business Intelligence.
Carlos is originally from Argentina, he was living for several years in Fort Lauderdale, Florida, working for Citibank. Then he started his own business.
Carlos is the creator of <a href="http://www.piFive.com">piFive</a>[<a target="_blank" title="piFive" href="http://www.piFive.com">^</a>], a family of BI Analytic Platform software, that it deals next to, <a href="http://www.latinsys.com">latinsys</a>[<a target="_blank" title="latinsys" href="http://www.latinsys.com">^</a>], his partner in businesses...
Currently he is sharing his passion for project management and BI at Citigroup.

Comments and Discussions

 
QuestionGrateful from Guangzhou, China Pin
Panxiaoma1-Feb-21 19:42
Panxiaoma1-Feb-21 19:42 
QuestionGrateful from Guangzhou, China Pin
Panxiaoma1-Feb-21 19:42
Panxiaoma1-Feb-21 19:42 
QuestionLicensing Pin
Member 1197735630-Sep-15 0:54
Member 1197735630-Sep-15 0:54 
GeneralMy vote of 5 Pin
wuditanke25-Nov-11 22:52
wuditanke25-Nov-11 22:52 
GeneralRe: My vote of 5 Pin
Member 108654124-Jun-14 23:33
Member 108654124-Jun-14 23:33 
GeneralHelp use these classes Pin
adekastos22-Dec-09 4:17
adekastos22-Dec-09 4:17 
Generalunicode Pin
Love In Snowing27-Jan-08 16:56
Love In Snowing27-Jan-08 16:56 
QuestionVERY URGENT Pin
Programm3r21-Aug-07 2:25
Programm3r21-Aug-07 2:25 
GeneralI Like it .... Pin
Programm3r27-May-07 21:55
Programm3r27-May-07 21:55 
GeneralThank you Pin
Yescode4-Aug-06 23:26
Yescode4-Aug-06 23:26 
QuestionProblems with ODBC and ntext in Visual c++ Pin
shsh2110-Jul-06 20:08
shsh2110-Jul-06 20:08 
Generalthank your source code! But... Pin
fivehun21-May-06 3:55
fivehun21-May-06 3:55 
GeneralRe: thank your source code! But... Pin
7649733328-Jun-09 21:59
7649733328-Jun-09 21:59 
GeneralToo inefficient! Pin
Tydia-kun30-Sep-05 1:11
Tydia-kun30-Sep-05 1:11 
Generaltoo many bugs!!!!!!!!!!!!!!!!!! Pin
miaolin7-Dec-04 2:17
miaolin7-Dec-04 2:17 
GeneralProblem while compiling the files in the DLL Pin
Member 138542915-Nov-04 19:59
Member 138542915-Nov-04 19:59 
GeneralExcel ODBC problem Pin
@LX9-Nov-04 11:54
@LX9-Nov-04 11:54 
GeneralConnect without using DSN Pin
24-Oct-04 22:34
suss24-Oct-04 22:34 
GeneralRe: Connect without using DSN Pin
2-Nov-04 19:39
suss2-Nov-04 19:39 
GeneralProblems with retriveing ntext field data Pin
playthegame16-Sep-04 23:20
playthegame16-Sep-04 23:20 
GeneralMicrosoft C++ Exception? help Pin
9999kkk12-Feb-04 4:46
9999kkk12-Feb-04 4:46 
Below SQLExecDirect function cause Microsoft C++ Exception in debug mode
If i change to <stop if="" not="" handled=""> in Exception dialog, it works anyway


SQLHSTMT hstmt;
TCHAR szSQL[1024];

retcode = SQLBindParameter(hstmt,..);
retcode = SQLBindParameter(hstmt,..);
retcode = SQLExecDirect (hstmt, (unsigned char *)szSQL, SQL_NTS);
Questionhow to access DBF files via ODBC and your class ? Pin
kostax18-Jan-04 23:14
kostax18-Jan-04 23:14 
Questionhow to insert long char data into database? Pin
jeam4-Jan-04 20:16
jeam4-Jan-04 20:16 
AnswerRe: how to insert long char data into database? Pin
jeam5-Feb-04 14:50
jeam5-Feb-04 14:50 
Answerhow to select lob field? Pin
jeam5-Feb-04 20:00
jeam5-Feb-04 20:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.