Solved QSqlDatabase - save/retrieve database to/from hard disk
-
Hi all,
I want to gain some experience with QT and database so I am studyng the Books example
https://doc.qt.io/qt-5.11/qtsql-books-example.html
My question is: would it possible to store that current database to hard disk, and retrieve it later after a program restart ?
If so, what QT's class shold I use or what is the preferred way to achieve this ?Thank you.
Regards,
s. -
@simozz Use SQLite as database for that - it is file based and supported by Qt.
-
Hi
To add to @jsulm
The reason its not saved to disk with that example is that in
books/initdb.h, function
QSqlError initDb()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");its set to be in memory
So you can change that to a file path and it will be stored on disk.db.setDatabaseName("c:\\somefolder\\dbname.db");
-
Hello again and thank you for the quick replies !
@jsulm Thanks, I will study better SQLite.
@mrjj Good to know your suggestion.
But what if the file already exists ?Do the function
db.setDatabaseName("c:\\somefolder\\dbname.db");
will overwrite the dbname.db content ?
I suppose it will not and I will have to check for already existing records.
Do you confirm ?Thanks.
s -
@simozz said in QSqlDatabase - save/retrieve database to/from hard disk:
setDatabaseName
Hi. it won't override as you would normally set it to open existing
DB and only in case the file not exist, it will be created.
Also, a DB can have multiple tables and hence if you want to clear all
records, you have to do that manually with SQL. -
Thank yoy @mrjj
-
@simozz
Hi
Just a small note.
You can use
qApp->applicationDirPath();
to get the path where exe is. Normally that is in the build folder. ( when you develop)
So you can use this to have a path to the DB that is always valid.
even on other machine.