Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Creating an SQLite database in Qt

From Wiki
Jump to: navigation, search

This example shows you how to create an SQLite database in Qt.

Article Metadata
Tested with
SDK: 4.7 and later (also tested 4.8)
Devices(s): Nokia 5800 XpressMusic, Nokia N900
Compatibility
Platform(s): Qt
Symbian
S60 5th Edition
Article
Keywords: QSqlDatabase, QSQlite, QSqlError
Created: tepaa (24 Nov 2009)
Reviewed: lilian.moraru (08 Nov 2012)
Last edited: hamishwillee (08 Nov 2012)

Contents

Preconditions

For Maemo SQLite development, the following packages must be installed:

  • libqt4-sql
  • libqt4-sql-sqlite
  • libsqlite3-0
  • libsqlite3-dev

Project file (.pro)

Add the following line to your .pro file

QT += sql

Header

#include <QObject>
#include <QSqlDatabase>
#include <QSqlError>
#include <QFile>
 
class DatabaseManager : public QObject
{
public:
DatabaseManager(QObject *parent = 0);
~DatabaseManager();
 
public:
bool openDB();
bool deleteDB();
QSqlError lastError();
 
private:
QSqlDatabase db;
};


Source

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();
}
 
QSqlError DatabaseManager::lastError()
{
// If opening database has failed user can ask
// error description by QSqlError::text()
return db.lastError();
}
 
bool DatabaseManager::deleteDB()
{
// Close database
db.close();
 
#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);
return QFile::remove(path);
#else
 
// Remove created database binary file
return QFile::remove("my.db.sqlite");
#endif
}


Postconditions

The database binary file is created on the device disk in Symbian & Windows and in the device memory in Maemo.


See also

This page was last modified on 8 November 2012, at 04:24.
1215 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×