Deleting data from a database in Qt
Jump to navigation
Jump to search
Overview[edit | edit source]
This example shows you how to delete data from 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]
- Qt is installed on your platform.
- S60:
- Download Qt release from here: Qt pre-release
- Install Qt: How to Install Qt
- Check this link for installation guide: How to install the package
- Qt Tower release has SQLite support. The required libraries are built into the Qt release.
- Maemo:
- More information about Qt on Maemo can be found here: Qt4 Maemo port
- S60:
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 DatabaseManager : public QObject
{
public:
DatabaseManager(QObject *parent = 0);
~DatabaseManager();
public:
bool openDB();
bool deletePerson(int id);
private:
QSqlDatabase db;
};
Source[edit | edit source]
Delete a person from the database:
bool DatabaseManager::deletePerson(int id)
{
bool ret = false;
if (db.isOpen())
{
QSqlQuery query;
ret = query.exec(QString("delete from person where id=%1").arg(id));
}
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]
A person's data is deleted from the database.