Sunday, 25 November 2012

Building a DSN less connection for OLE DB

Needed to hook a Windows application to an MS-Access database . The windows application would insert records into the tables when the end user choose one of the application's menu option.

I thought that it would be good idea to free up the end user from having to create the databases DSN using the ODBC data source administrator control panel. A DSN less connection string look like this

"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\myapplication\\mycooldb.accdb"

The only down size of this is that I would have to hard code this somewhere on the source code.

Wait! Since the database will be distributed with the application what about if  'Data Source"' property gets built dynamically.

To achieve this it's need to retrieve the directory of the running application , append to this the database name and make sure that the Provider property is included.

CString myDatabasePath;
CString connString (_T("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = "));

//this get the file path of the application ,chop  off the executable name and
// add the database name
GetModuleFileName(NULL,myDatabasePath.GetBufferSetLength(MAX_PATH),MAX_PATH);
myDatabasePath.Truncate(targetDir.ReverseFind('\\') + 1) ;
myDatabasePath +=        "mycooldb.accdb";

// add the database path (i.e C\myapplication\\mycooldb.accdb) to the connection string
connString += myDatabasePath

//need to do this since  OLE DB is used
BSTR bstrConnString = connString.AllocSysString();
hr = _db.OpenFromInitializationString(bstrConnString);

//free up string used
targetDir.ReleaseBuffer(MAX_PATH);
SysFreeString(bstrConnString);