Click here to Skip to main content
15,867,453 members
Articles / Desktop Programming / MFC
Article

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 107K   1.7K   35   8
About my experience of coding a database related program using MFC with VC6
Download adofinal.zip - 324.91 KB

Introduction

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.

Background

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.

Questions:

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:

SQLConfigDataSource(
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;

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


//DataSourceTest is a data source name

m_database.Open("DataSourceTest");

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");
m_database.ExecuteSQL(strSQL);

//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

}else{

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

//Get value of field 'upwd'

m_recordset.GetFieldValue("upwd", password);

}

m_recordset.Close();
m_database.Close();

License

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 1:47
Member 102932602-Jun-14 1:47 
QuestionWaiting for more details to be revailed~ Pin
WiStRoM19-Dec-12 7:05
WiStRoM19-Dec-12 7:05 
GeneralMy vote of 4 Pin
Louai Haimour14-Dec-12 0:34
Louai Haimour14-Dec-12 0:34 
QuestionCan You do me little bit help....About DLL.. Pin
vijay.victory19-May-10 19:01
vijay.victory19-May-10 19:01 
Generalgood article! Pin
nilei12311-Jan-10 0:40
nilei12311-Jan-10 0:40 
GeneralKeep a Blog and make an article when you're finished Pin
bolivar1236-Jan-08 0:09
bolivar1236-Jan-08 0:09 
GeneralRe: Keep a Blog and make an article when you're finished Pin
grin_t6-Jan-08 1:12
grin_t6-Jan-08 1:12 
GeneralRe: Keep a Blog and make an article when you're finished Pin
sadjad.k1-Jan-10 11:13
sadjad.k1-Jan-10 11:13 
Thanks. I had to begin from somewhere and it was good begining to me Smile | :) Thumbs Up | :thumbsup:

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.