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.

Inserting a row into a database in Qt

From Wiki
Jump to: navigation, search
Article Metadata
Tested with
Devices(s): Nokia 5800 XpressMusic
Platform(s): Qt
Keywords: QSqlDatabase, QSQlite, QSqlError, QSqlQuery
Created: tepaa (09 Sep 2009)
Last edited: hamishwillee (11 Oct 2012)



This example shows you how to insert data into an SQLite database in Qt. We show how to use an autoincrement field that generates a new ID for the new row automatically.

The table 'person' has the following columns:

  • id (integer primary key), this is an autoincrement field
  • firstname (varchar(20))
  • lastname (varchar(30))
  • age (integer)


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

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


#include <QObject>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
class DatabaseManager : public QObject
DatabaseManager(QObject *parent = 0);
bool openDB();
bool createPersonTable();
int insertPerson(QString firstname, QString lastname, int age);
QSqlDatabase db;


The following code inserts a new row (person) and the autoincrement field generates a new ID for the row. Next, the newly generated ID is queried.

int DatabaseManager::insertPerson(QString firstname, QString lastname, int age)
int newId = -1;
bool ret = false;
if (db.isOpen())
// NULL = is the keyword for the autoincrement to generate next value
QSqlQuery query;
ret = query.exec(QString("insert into person values(NULL,'%1','%2',%3)")
// Get database given autoincrement value
if (ret)
newId = query.lastInsertId().toInt();
return newId;

The rest of the code:

bool DatabaseManager::createPersonTable()
// Create table "person"
bool ret = false;
if (db.isOpen())
QSqlQuery query;
ret = query.exec("create table person "
"(id integer primary key, "
"firstname varchar(20), "
"lastname varchar(30), "
"age integer)");
return ret;
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 = QDir::toNativeSeparators(path);
// NOTE: File exists in the application private folder, in Symbian Qt implementation
// Open databasee


A new person is added into the database.

See also

This page was last modified on 11 October 2012, at 01:17.
502 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.