Monday, November 19, 2007

Retrieving a List of All ODBC Data Sources

The Open Database Connectivity (ODBC) API contains a function called SQLDataSources() which can be used to retrieve information about data sources which are available to an application. Below is a code snippet which fills a CStringArray with the names of all available ODBC data sources in the system.

Please include ODBC32.lib in your application before building.

   #include "sqlext.h"
 
   #define MAX_DSN_LENGTH 30
   #define MAX_DSN_DESC_LENGTH 300

HENV hEnv;

char szDSN[MAX_DSN_LENGTH];

SWORD cbDSN;

UCHAR szDescription[MAX_DSN_DESC_LENGTH];

SWORD cbDescription;

RETCODE retcode;

CStringArray * pArray= new CStringArray;

SQLAllocEnv(&hEnv);

while (retcode=SQLDataSources(hEnv, SQL_FETCH_NEXT,

(UCHAR FAR *) &szDSN, MAX_DSN_LENGTH, &cbDSN,

(UCHAR FAR *) &szDescription,MAX_DSN_DESC_LENGTH,

&cbDescription) != SQL_NO_DATA_FOUND

&&retcode!=SQL_ERROR)

{

pArray->Add( szDSN );

}

Now pArray contains the names of all the ODBC data sources available in the system.

No comments: