Classes for direct SQL calls with ODBC


During my current project, I found that I needed more functionality with my
sql calls than CRecordset or CDAORecordset had to offer. These classes wrap
the low-level ODBC API calls and act simular to a CRecordset, but allow me
to execute any SQL statement without having to bind variables,etc.

The main class for doing this is CSQLDirect. CSQLDirect has the following

  • CSQLDirect::Connect – Connects to a datasource.
  • CSQLDirect::ExecuteSQL – this is the main function that is used for
    handling the SQL statement.

  • CSQLDirect::GetCol – Will return a column from a table in the resulting

  • CSQLDirect::GetError – Provides detailed error messages in case something
    went wrong.

  • CSQLDirect::GetColumnType – Provides information about a cursor’s column.
  • CSQLDirect::Fetch – Will properly execute a SQLFetch command with error

  • CSQLDirect::Close – Closes the connection to the datasource.

The other class CSQLColumn is a support class for CSQLDirect. Since
multiple queries to a cursor’s column will result in a NULL value being
returned, I found it necessary to keep track of the columns as they are
used. This is stored in a CPtrArray within CSQLDirect and is cleaned up
after each time the cursor is requeried/closed.

An example of using this class to make SQL Calls:

CSQLDirect SQLDirect( "TestData" );

if( SQLDirect.ExecuteSQL( "SELECT * FROM Employee" )==SQL_SUCCESS ) {
	while( SQLDirect.Fetch()==SQL_SUCCESS ) {
		// Do some stuff here

That’s it!

The great thing about this class is you no longer have need for a huge
assortment of CRecordset classes for every table/query.

Anyways I hope this can be of help to anyone that uses the site. Don’t
hesitate to give me a shout if anyone has any questions/comments.

Thanks for all the help that CodeGuru has given my over the last few months!

Download Source 3K

More by Author

Must Read