4

Is there a way to reference 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 database.sqlite to the Resources folder and call it via qrc:, but apparently it is not possible to write to a resource file.

  • I also tried using QApplication::applicationDirPath();, but this would result in different paths depending on the user's OS. E.g. it appends MyApp.app/Contents/MacOS to the actual directory.

alex
  • 4,922
  • 7
  • 37
  • 51

2 Answers2

2

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

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

So you must know absolute path of your db in your case.

edit

In the case you initially know where the database should be located you can either hardcode it (which is never wise) or you can create a configuration and load it using QSettings. For example:

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

Take a look further here

Neox
  • 2,000
  • 13
  • 12
  • In my app for example I build up an absolute path from my configuration. We have a multiuser environment and depending on the username I build up a home directory and so on. What requirements do you have for your application? – Neox Jan 23 '12 at 17:56
  • Well basically I want to create a .sqlite DB on first startup and then use that DB whenever the user starts the app again. So nothing really fancy about that :) – alex Jan 23 '12 at 18:04
  • Thanks for the edit. But does that change anything? I still can't just reference the path to database.sqlite, because it depends on the place it is executed and on the system it is executed on? – alex Jan 23 '12 at 18:40
  • The path to the db does depends on the platform, so with sqlite in the end you have to decide on where you want to store the db – Neox Jan 23 '12 at 18:48
  • @alex how did you get it.Is it worked fine.Do you have any solution for get it.I have got issuse same you.:( – Brian Jul 13 '13 at 10:36
0

if you want to store the db per user you shout use this:

QDesktopServices::storageLocation(QDesktopServices::DataLocation)

this method returns the location where persistent application data can be stored.

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

nickel715
  • 2,505
  • 1
  • 23
  • 28