Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a SQLite database in Qt

I am trying to create a SQLite database in Qt. Here is my code:

QDir databasePath;
QString path = databasePath.currentPath()+"myDb.db";
QSqlDatabase dbConnection = QSqlDatabase:addDatabase("QSQLITE");
db.setDatabaseName(path);
db.open();

There are no errors when running the code, but I can't find the database I created in the path I defined. Does this actually create the database or does it just do some initialization?

If it does not create the database then how do I create the database within the application itself? (I am not talking about insertion.)

like image 609
user3009135 Avatar asked Jan 08 '15 16:01

user3009135


People also ask

What is SQLite in Qt?

SQLite is a small C library that implements a self-contained, embeddable, zero-configuration SQL database engine. Used in Qt SQL Lite plugin. Configure Qt with -system-sqlite or -no-sqlite to avoid. The sources can be found in qt5/qtbase/src/3rdparty/sqlite.

How do I create a database in SQLite studio?

To create a database, click on “Database” then “Add a database”. In the next window that appears (the left one below), click on the green “+” to create a new database.


1 Answers

You should also create query which will create not empty database and use correct name of variable(in your code you use dbConnection firstly and after that - db. For example:

QString path = "path";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//not dbConnection
db.setDatabaseName(path);
db.open();
QSqlQuery query;
query.exec("create table person "
          "(id integer primary key, "
          "firstname varchar(20), "
          "lastname varchar(30), "
          "age integer)");
like image 103
Kosovan Avatar answered Oct 07 '22 00:10

Kosovan