Searching for data in a database in Qt
Jump to navigation
Jump to search
Overview[edit | edit source]
This example shows you how to search for data in an SQLite database in Qt.
The table 'person' has the following columns:
- 76ytuiytuityutyutututyutyutyu, this is an autoincrement field
- 76ytuiytuityutyutututyutyutyu
- 76ytuiytuityutyutututyutyutyu
- 76ytuiytuityutyutututyutyutyu
Preconditions[edit | edit source]
For Maemo SQLite development, the following packages must be installed:
- libqt4-sql
- libqt4-sql-sqlite
- libsqlite3-0
- libsqlite3-dev
Header[edit | edit source]
- include <QObject>
- include <QSqlDatabase>
- include <QSqlError>
- include <QSqlQuery>
- include <QString>
class PersonData
{
public:
int id;
QString firstname;
QString lastname;
int age;
};
class DatabaseManager : public QObject
{
public:
DatabaseManager(QObject *parent = 0);
~DatabaseManager();
public:
bool openDB();
bool getPerson(int id, PersonData*& person);
private:
QSqlDatabase db;
};
Source[edit | edit source]
Search for person data from the database:
bool DatabaseManager::getPerson(int id, PersonData*& person)
{
bool ret = false;
QSqlQuery query(QString("select * from person where id = %1").arg(id));
if (query.next())
{
person->id = query.value(0).toInt();
person->firstname = query.value(1).toString();
person->lastname = query.value(2).toString();
person->age = query.value(3).toInt();
ret = true;
}
return ret;
}
The rest of the code:
bool DatabaseManager::openDB()
{
// Find QSLite driver
db = QSqlDatabase::addDatabase("QSQLITE");
#ifdef Q_OS_LINUX
// NOTE: We have to store database file into user home folder in Linux
QString path(QDir::home().path());
path.append(QDir::separator()).append("my.db.sqlite");
path = QDir::toNativeSeparators(path);
db.setDatabaseName(path);
#else
// NOTE: File exists in the application private folder, in Symbian Qt implementation
db.setDatabaseName("my.db.sqlite");
#endif
// Open databasee
return db.open();
}
Postconditions[edit | edit source]
Person data is searched from the database.