Search This Blog

Wednesday, May 6, 2009

DSN Less ODBC Database Connection in Win32 VC++

Intro
You may be familiar with the Database connectivity in applications. We need to design a database with tables, columns, rows and all.. and atlast need a DSN to connect our application to Database.


Actually, while creating a DSN, the Config Wizard dialog prompts you to choose a driver for the type of database which you're using.


This driver acts as a bridge of communication b/w our application and the database engine. I'm not going into further details.. Consider you have SQL database, created a DSN and configured,.. fine, our application will work with database connected and you'll be happy.


But, if you try to copy it in your friend's system, what will be the case?? Well.. it wont work unless you've configured and created a DSN. Suppose, there is no SQL Driver installed in that machine? oops... thats a weird situation.


So, what if i can connect to a database, without DSN to be configured each time.. and using a common driver which ships with the Operating System(Windows).. lol, here is a sample code for doing it.

Hot to Do it?

Well, we have SQLDriverConnect() API to do this task for us. All we have to do is pass a Connection string, pointing our database file path, its username and password etc.

Code Snip:

SQLRETURN retcode;
SQLHDBC hdbc;
HWND desktopHandle = GetDesktopWindow(); // get desktop's window handle
.....................//Code for Allocating environment handle,
........................ //ODBC version environment attribute,
.........................//Allocate connection handle, and set login timeout(Optional)
retcode = SQLDriverConnect( hdbc, desktopHandle, (SQLCHAR*) "Driver={Microsoft Access Driver *.mdb)};Dbq=C:\\mydatabase.mdb;Uid=Admin;Pwd=;", _countof( "Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\\mydatabase.mdb;Uid=Admin;Pwd=;"), OutConnStr, 255, &OutConnStrLen, SQL_DRIVER_NOPROMPT );

...........
...................
...........

if it connected sucessfully, retcode will have either SQL_SUCCESS or SQL_SUCCESS_WITH_INFO value returned from SQLDriverConnect(). Now you can execute your database queries by using SQLPrepare() and SQLExecute() API's after Allocating SQL Handle (SQLAllocHandle()) and SQLAllocStmt(). Read MSDN documentation for more about SQL API's. :-)

PS : Leave your comments and help me improve :-)

No comments:

Post a Comment