Knowledge Base

How to use the MFC database classes in a console application in Visual C++

Article ID: 152696

Article Last Modified on 11/21/2006


APPLIES TO


This article was previously published under Q152696

SUMMARY

The MFC database classes found in Visual C++ versions 1.x, 2.x, 4.0, and 4.1 were not written to be used in a console application. However, with some modification, you can use the 32-bit database classes in a console application. The techniques presented here apply to both the MFC ODBC and MFC DAO classes.

Starting with Visual C++ 4.2, the MFC ODBC classes were rendered safe for use within console applications. Many of the internal dependencies listed below are no longer present in the 4.2 and later MFC ODBC class libraries.

MORE INFORMATION

Both the MFC ODBC and MFC DAO classes have dependencies upon non-Database MFC classes, particularly with the existence of a global CWinApp-derived object. The following list presents these dependencies along with suggestions for working around them.

For either MFC ODBC or MFC DAO, it is very important to test your code not only for successful execution, but for graceful recovery on unexpected conditions (such as the database not being in an expected path). The majority of the "dependencies" these classes have on MFC come from error recovery and reporting code within the database classes.

It is also important to remember that the Visual C++ MFC database classes released through version 4.1 were not intended or tested for use in a console application.

Both MFC ODBC and MFC DAO classes

  • Exception handling

    Microsoft recommends that you wrap exception handling code around each of your calls to an MFC Database class method.
  • Exception handling and resource handles

    Internally, MFC ODBC uses AfxThrowDBException to throw exceptions, and MFC DAO uses AfxThrowDaoException() to throw exceptions. Both functions can result in a call to CString::LoadString(), which requires a resource handle for the application. In addition, the MFC DAO method CDaoException::GetErrorMessage(), used to get more information about a DAO error, also calls CString::LoadString().

    Within CString::LoadString() is a call to AfxLoadString(), which calls AfxGetResourceHandle(), which expects a valid resource handle to be defined for the EXE.

    To work around this, define a valid resource handle for your application as shown in this code:
          hMod = ::GetModuleHandle( "MyApp.Exe" );
          ASSERT( hMod );
          AfxSetResourceHandle( hMod );
    						

MFC ODBC classes

MFC DAO classes

The MFC DAO classes are relatively independent of the MFC library. However here are some considerations to keep in mind when using them in a console application:

Additional query words: kbvc200 kbvc210 kbvc220 kbvc400 kbvc410 kbvc420 kbvc500 kbvc600

Keywords: kbdao kbinfo kbdatabase kbhowto kbprogramming kbusage KB152696