Solved Qt + SQLite Tutorial
-
Hi all:
I need to create an app to manage data of a study. I have created the UI using Qt but I need a tutorial to connect my UI to a database (SQLite).
Can anyone provide me a Tutorial of how to connect both?
Thank you very much in advance.
P.D: I have tried some tutorial but no one give me enough information.
I am using Windows 10
-
http://doc.qt.io/qt-5/qtsql-cachedtable-example.html
Look at createconnection method and change do filename like follows
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("tom.db"); -
Thanks.
How could I split the way to insert data?? I want separate the connection to the database from the insert.
Thank you very much in advance.
-
You can basically split the routine everywhere after each step. The first step is the DB connection and its error handling. Afterwards you can put every query step into a separate routine e.g.
bool routine1 () { QSqlQuery query; query.exec("create table person (id int primary key, firstname varchar(20), lastname varchar(20))"); return true; }
and
bool routine2 () { QSqlQuery query; query.exec("insert into person values(101, 'Danny', 'Young')"); return true; }
The db conenction kept internally somewhere.
-
Thank very much indeed.
Last question about database. tom.db have been created in the root directory. Is it possible create it in a directory(Not including the path in the String)??
-
You can add a path to your db name.
E.g. with
db.setDatabaseName("c:/data/testing/databases/tom.db");
This is an example for windows. Similar you can do it for linux or any other system.
Note: you need to create the path to your DB manually outside or with Qt in your program. -
Thanks.
Amazing!!! The database is created automatically.
-
@dheerendra I have tried this but keep getting loads of errors , i think i need to configure my QT to work with SQLite but dont know how i can do this
-
What errors? QMake or CMake?
If you have apro
file, have you addedQT += sql
?