Create Access data source name dynamically

This sample in this article was created using VC 5.0. The necessary .h and .lib files are present in the zip.

To create a DSN at run time you could use the SQLConfigDataSource API. Internally this information is stored in the registry. The syntax is attached below

SQLConfigDataSource(NULL,ODBC_ADD_DSN,"Microsoft Access Driver (*.mdb)\0","DSN=TestDB\0DBQ=D:\\Database\\Friends.mdb\0DEFAULTDIR=D:\\DATABASE\0\0");

The problem is that if you want to accept the values from the user or set these values at run time by passing CString or char* will not work. This is because, when sprintf encounters a /0 it assumes it is the end of the string and ignores the rest of the data.

As a workaround you have to use the below mentioned code.

The following code places : where a /0 is expected and there is a loop which replaces a ":" with "/0". You will not be in a position to use sprintf because, when it encounters a /0 it assumes it is the end of the string and ignores the rest of the data.

char* szDesc;

int mlen;

szDesc=new char[256];

sprintf(szDesc,"DSN=%s: DESCRIPTION=TOC support source: DBQ=%s: FIL=MicrosoftAccess: DEFAULTDIR=D:\\Database:: ","TestDB","D:\\Friends.mdb");

mlen = strlen(szDesc);

for (int i=0; i<mlen; i++)

{

if (szDesc[i] == ':')

szDesc[i] = '\0';

}

if (FALSE == SQLConfigDataSource(NULL,ODBC_ADD_DSN,"Microsoft Access Driver (*.mdb)\0",(LPCSTR)szDesc))

MessageBox(hwnd,"Failed","INFORMATION",MB_OK);

else

MessageBox(hwnd,"Sucess","INFORMATION",MB_OK);

Download ZIP - 48KB