Qt SQLite database without absolute path

Is there a way to link to the database.sqlite file without knowing the absolute path?

_db = QSqlDatabase::addDatabase("QSQLITE"); _db.setDatabaseName("/the/path/i/dont/know/database.sqlite"); 
  • I already tried to add the .sqlite database to the Resources folder and name it with qrc: but apparently it is impossible to write to the resource file.

  • I also tried using QApplication::applicationDirPath(); , but this will lead to various paths depending on the user OS. For instance. it adds MyApp.app/Contents/MacOS to the actual directory.

+4
source share
2 answers

When you create a QSqlDatabase with SQLite as the backend, you have two options:

  • Give an absolute path as db name
  • Give a relative path: in this case the database will be stored in the directory of your binary file.

So, you should know the absolute path of your dB in your case.

change

In the event that you initially know where the database should be located, you can either copy it (which is never reasonable), or you can create a configuration and load it using QSettings. For instance:

 QSettings settings; QString dbPath = settings.readValue("DBPath", QString(/*fallback path*/)).toString(); //do smth with dbPath 

Look further here

+2
source

if you want to keep db for every user you shout use this:

 QDesktopServices::storageLocation(QDesktopServices::DataLocation) 

this method returns the location in which persistent application data is stored.

for more information check this: http://doc.trolltech.com/4.5/qdesktopservices.html#storageLocation

0
source

Source: https://habr.com/ru/post/1392507/


All Articles