Creating a database table in Qt
Article Metadata
Tested with
Devices(s): Nokia 5800 eXpressMusic, Nokia N900
Compatibility
Platform(s): Qt
Article
Keywords: QSqlDatabase, QSQlite, QSqlError, QSqlQuery
Created: (09 Sep 2009)
Last edited: tepaa
(11 Sep 2009)
Contents |
Overview
This example shows you how to create 'person' table into (SQLite) database in Qt.
Table person has following columns
- id (integer primary key), this is autoincrement field http://www.sqlite.org/autoinc.html
- firstname (varchar(20))
- lastname (varchar(30))
- age (integer)
Preconditions
- Qt is installed on your platform
- S60
- Download Qt for S60 release from here: Qt for S60 pre-release
- Install Qt for S60: Installing Qt on S60
- Check this link for installation guide: How to install the package.
- Qt for S60 Tower release has SQLite support. Needed libraries are bilt in the Qt release.
- S60
- Maemo
- More information about Qt on Maemo can be found here: Qt4 Maemo port
- Maemo
Maemo SQLite development needs following packages to be installed:
- libqt4-sql
- libqt4-sql-sqlit
- libsqlite3-0
- libsqlite3-dev
Header
#include <QObject>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
class DatabaseManager : public QObject
{
public:
DatabaseManager(QObject *parent = 0);
~DatabaseManager();
public:
bool openDB();
bool createPersonTable();
private:
QSqlDatabase db;
};
Source
Create "person" table.
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;
}
Rest of the code...
bool DatabaseManager::openDB()
{
// Find QSLite driver
db = QSqlDatabase::addDatabase("QSQLITE");
#ifdef Q_OS_LINUX
// in Maemo we create database into memory because
// it does not work from file
db.setDatabaseName(":memory:");
#else
// Set database to be created into file.
// In Symbian file exists in the application private folder
db.setDatabaseName("my.db.sqlite");
#endif
// Open databasee
return db.open();
}
Postconditions
Database table "person" created.
See also
- Tools:Creating SQLite database in Qt
- Tools:Creating database table in Qt
- Tools:Insert row into database in Qt
- Tools:Search data from the database in Qt
- Tools:Delete data from database in Qt
- Select data from database without using SQL statements in Qt
- Tools:Using QDataWidgetMapper for showing data from database in Qt

