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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

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?
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 :)
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?
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
@alex how did you get it.Is it worked fine.Do you have any solution for get it.I have got issuse same you.:(
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.