Click here to Skip to main content
15,566,522 members
Articles / Desktop Programming / MFC
Posted 5 Jan 2008


35 bookmarked

Using Database in your MFC program - A beginner's experience

Rate me:
Please Sign up or sign in to vote.
2.60/5 (17 votes)
10 Jul 2008CPOL4 min read
About my experience of coding a database related program using MFC with VC6
Download - 324.91 KB


Currently I'm a beginner of MFC programming. So I understand how puzzled and anxious a beginner will be when he begin to program using MFC. I don't mean that MFC is too difficult to understand by a beginner (though it is not easy).

No matter what programming environment you are using (vc6 or vc >6 (I use VC6)), you'll find that MFC is one thing that you must learn (sooner or later). And you'll find it a bit strange if you have been used to making programs running under console. You cannot find the main function, and puzzled with where to type your code, and problems of this kind. But, what I want to say is, there's just one step between console and graphical based programming! And what I want to do is to make this step easier.


A month ago, one of my friends come to me and asked me to make a program for him and gave me 6 months. I consented to him without consideration. (He's one of my best friend you know)

And the fact is that, the program is graphical based and must be run with a databased connected. And by that time, I even don't know exactly what MFC is.

Under the help of the internet and, which is more important, another one of my best friends. Things becomes much better now, though the program hasn't been finished yet. What I have now is a dialog window with a few controls, and with a database connected. And I decide to put the problems and the solutions here. I hope it will be helpful to those who new to MFC.

Whenever new problems have been solved, I'll append it here. And I'll do this job (weekly because I'm still in school) until the completion of the program.


1. How can I create a data source within the code?
2. What shall I do when I have created the data source?

The Data Source (*.mdb)

There are 3 things must be done before creating the data source.

1. Prepare a database (eg: test.mdb)
2. Import library "odbccp32.lib" (Project->Add to project->Files). Path of the file in my computer "C:\Program Files\Microsoft Visual Studio\VC98\Lib".
3. Include head file ("#include <odbcinst.h>")

addtoproject.JPG insert.GIF

By using:
SQLConfigDataSource(HWND hwndParent, UINT fRequest, LPCSTR lpszDriver, LPCSTR lpszAttributes);

one can create a data source within his code. (For more details about this function, please look into MSDN.)
The sample code is:

NULL, ODBC_ADD_DSN, "Microsoft Access Driver (*.mdb)\0", "DSN=TheDataSourceName\0DBQ=X:\\dbpath\\dbfilename\0DEFAULTDIR=X:\\dbpath\0\0");

//ODBC_ADD_DSN means to create a data source
//You can try ODBC_REMOVE_DSN to remove the data source

//The function below is used to generate the 4th parameter which contains
//data source name, database's file name and the database's path

The forth parameter can be generated by the function below:

void getAdoStr(

char * str,

char dbfile[],

char dbname[],

char linkstr[] = "DSN=%s!DBQ=%s!DEFAULTDIR=%s!!")


//str = Result

//dbfile[] = file name (eg:test.mdb)

//dbname[] = data source name

char szAtr [256];

CString szPath, szFile;

int nPos, nlen, i;

GetModuleFileName(NULL, szPath.GetBufferSetLength (MAX_PATH+1), MAX_PATH);

szPath.ReleaseBuffer ();

nPos=szPath.ReverseFind ('\\');

szPath=s<code>zPath.Left (nPos);

szFile = szPath + "\\" + dbfile;

sprintf (szAtr, linkstr, dbname, szFile, szPath);

nlen = strlen (szAtr);

for (i=0; i<nlen; i++){

if (szAtr [i] == '!'){

szAtr [i] = '\0';



for (i=0; i<nlen; i++){

str [i] = szAtr [i];



CDatabase and CRecordset

Create data source is just the first step. The next step is to use the database.
CDatabase class represents a connection to a data source.
CRecordset class is usually used to select records from forms.

CDatabase m_database;

CRecordset m_recordset;
CString strSQL;
CString username;
CString password;

"Microsoft Access Driver (*.mdb)\0",

//DataSourceTest is a data source name


m_recordset.m_pDatabase = &m_database; //tell CRecordset where to find the database

//Insert a record into database

strSQL.Format("insert into user(uname, upwd) values(%s, '%s')", "admin", "pwd");

//Select the record (uname='admin' and password='pwd')
strSQL.Format("select * from user where uname='%s' and upwd='%s'", "admin", "pwd");
m_recordset.Open(CRecordset::forwardOnly, strSQL);

//Get the number of the selected records
if (m_recordset.GetRecordCount() == 0){

//no record found


//Get value of field 'uname'
m_recordset.GetFieldValue("uname", username);

//Get value of field 'upwd'

m_recordset.GetFieldValue("upwd", password);




This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Other School
China China
At the moment, a beginner.

Comments and Discussions

GeneralMy vote of 1 Pin
Member 102932602-Jun-14 2:47
Member 102932602-Jun-14 2:47 
QuestionWaiting for more details to be revailed~ Pin
WiStRoM19-Dec-12 8:05
WiStRoM19-Dec-12 8:05 
GeneralMy vote of 4 Pin
Louai Haimour14-Dec-12 1:34
Louai Haimour14-Dec-12 1:34 
QuestionCan You do me little bit help....About DLL.. Pin
vijay.victory19-May-10 20:01
vijay.victory19-May-10 20:01 
Generalgood article! Pin
nilei12311-Jan-10 1:40
nilei12311-Jan-10 1:40 
GeneralKeep a Blog and make an article when you're finished Pin
bolivar1236-Jan-08 1:09
bolivar1236-Jan-08 1:09 
Perhaps you should wait until your project is finished to try to make a CP article from your experience at that time?
GeneralRe: Keep a Blog and make an article when you're finished Pin
grin_t6-Jan-08 2:12
grin_t6-Jan-08 2:12 
GeneralRe: Keep a Blog and make an article when you're finished Pin
sadjad.k1-Jan-10 12:13
sadjad.k1-Jan-10 12:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.