Introduction
These C++/MFC classes simplify access to SQLite databases from your MFC applications. SQLite native API is quite simple and documentation is very good so it will take you about one day to start using it - and with these two classes, you will do the same job in minutes. ;)
Please download the full source code with sample application here.
Using the Code
To add SQLite access to your MFC application, please add the files from the sample application \database\ folder to your project. After that, please:
#include
the SQLiteDatabase.h and SQLiteRecordset.h to your source code - Create an instance of the
CSQLiteDatabase
class. It will be a good idea to make it a member of your CWinApp
application class or a member of an application window class - Connect to the database by using the
CSQLiteDatabase::Connect()
method. - If you need to launch a query that does not return a
recordset
, please use the BOOL CSQLiteDatabase::Query(LPCTSTR szQuery, CString &sError)
method - If you need to launch a query that returns a
recordset
, please:
- Create an uninitialized (
NULL
) pointer to an instance of the CSQLiteRecordset
class - Use the
BOOL CSQLiteDatabase::Query(LPCTSTR szQuery, CString &sError, CSQLiteRecordset **ppRecordset)
method, passing the pointer to the pointer you've created above in the 3rd query parameter - Navigate through the records by using the
CSQLiteRecordset::Next()
method - Read the data from the database by using the
CSQLiteRecordset::AsInteger(int number), CSQLiteRecordset::AsString(int number)
, etc. methods - Use the
CSQLiteRecordset::Close()
method after you'll finish with reading data.
- After your database job will be completed, please close the database connection by using the
CSQLiteDatabase::Disconnect()
method.
Usage Sample
Below, please find the code that demonstrates the class usage. This code fragment opens a database, prints records from this database on the screen and then closes connection to the database:
#include "SQLiteDatabase.h"
#include "SQLiteRecordset.h"
void printDatabase(void)
{
CString sError;
CSQLiteDatabase sqlDatabase;
if (!sqlDatabase.Connect("C:\\database.sqlite", NULL, NULL, sError)
{
AfxMessageBox("Failed to connect to the database: " + sError);
return;
}
CSQLiteRecordset *pRecordset = NULL;
if (!sqlDatabase.Query
("SELECT last_name FROM employee", sError, &pRecordset))
{
AfxMessageBox("Failed to query the database: " + sError);
sqlDatabase.Disconnect();
return;
}
while (pRecordset->Next())
AfxMessageBox(pRecordset->AsString(0));
pRecordset->Close();
delete pRecordset;
pRecordset = NULL;
sqlDatabase.Disconnect();
}