Introduction
Today in many projects, we need a database for our application as a result of which we have to link to the database file from our application. With this tip, we can connect to
a database from MFC and query or get a report from that.
Background
To get information on this subject, you can read or search about Connect to database from application.
Algorithm and Simulating the Algorithm in Code
At first, we have to determine what database is required. With the choice of
a combobox, we decide what string connection to the database is needed. If we choose Access Database, our string connection is like below:
Driver={Microsoft Access Driver (*.mdb)};Server:.;Dbq=db.mdb;Uid=;Pwd=;
and if we choose Excel Database, that's like:
Driver={Microsoft Excel Driver (*.xls)};
DriverId=790;bq=C:\\DatabasePath\\DBSpreadSheet.xls;DefaultDir=c:\\databasepath;
and if we choose SQL Database, that will be:
Driver={SQL Server Native Client 11.0};Server=.;
AttachDbFilename=shop.mdf;Database=shop;Trusted_Connection=Yes;
After that, we run a query on the database. We have to make sure that the query's type is Reporting Query or Execute Query.
The queries that get information from the database are Reporting Queries like "select * from table
". And other queries that do work or affect the database are Execute Queries like "update id form table1 where name='mahdi'"
. To determine this algorithm, we write a function to get the query string and determine that with the below code:
bool IsReport(CString code){
code.TrimLeft();code.TrimRight();code.MakeLower();
if(code.Left(6)==_T("insert")||code.Left(6)==_T("update"))return 0;
return 1;
}
Now we decide to get a report from the database or send an execute query with the above function. If
the IsReport()
function returns 0
, it means that we have to send the query as a getting report or else we have to send the query as an execute query.
Statements like insert
, update
,.... affect the database, so these are execute queries and we send these queries in CDatabse
and other statements get reported and we send these with
the CRecordset
class. The CDatabase
class can do execute and CReordset
can fields of queries. With this code, you can get
do it better:
CString query;
tquery.GetWindowText(query);
list.ResetContent();
if(IsReport(query)){ CRecordset recordset(&database);
CString temp,record;
recordset.Open(CRecordset::forwardOnly,query,CRecordset::readOnly);
while(!recordset.IsEOF()){ record=_T("");
register int len=recordset.GetODBCFieldCount();
for(register int i=0; i < len ; i++){
recordset.GetFieldValue(i,temp);
record+=temp+_T(" | ");
}
list.AddString(record);
recordset.MoveNext();
}
}else{
database.ExecuteSQL(query);
}
MessageBox(_T("Query done."),0,0);
I hope this will be useful for you. Thanks in advance.