Creating an SQLite database in Qt

From Qt Wiki
Jump to navigation Jump to search

Template:Abstract

Template:ArticleMetaData

Preconditions[edit | edit source]

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

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

Project file (.pro)[edit | edit source]

Add the following line to your .pro file QT += sql

Header[edit | edit source]

  1. include <QObject>
  2. include <QSqlDatabase>
  3. include <QSqlError>
  4. include <QFile>

class DatabaseManager : public QObject

   {
   public:
       DatabaseManager(QObject *parent = 0);
       ~DatabaseManager();
       
   public:
       bool openDB();
       bool deleteDB();
       QSqlError lastError();
   private:
       QSqlDatabase db;
   };


Source[edit | edit 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[edit | edit source]

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


See also[edit | edit source]