20

I am trying to create a SQLite database in Qt. Here is my code:

QDir databasePath;
QString path = databasePath.currentPath()+"myDb.db";
QSqlDatabase dbConnection = QSqlDatabase:addDatabase("QSQLITE");
db.setDatabaseName(path);
db.open();

There are no errors when running the code, but I can't find the database I created in the path I defined. Does this actually create the database or does it just do some initialization?

If it does not create the database then how do I create the database within the application itself? (I am not talking about insertion.)

3
  • 1
    Hard code the path instead of creating a variable, and test again. That is one way to ensure it isn't a code or bad string issue as opposed to some other issue. Commented Jan 8, 2015 at 16:28
  • @PaulMcKenzie: this is actually solved the problem of the location thank you very much Commented Jan 8, 2015 at 16:39
  • The most common mistake here is to get the path wrong. Commented Jan 8, 2015 at 16:57

2 Answers 2

32

You should also create query which will create not empty database and use correct name of variable(in your code you use dbConnection firstly and after that - db. For example:

QString path = "path";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//not dbConnection
db.setDatabaseName(path);
db.open();
QSqlQuery query;
query.exec("create table person "
          "(id integer primary key, "
          "firstname varchar(20), "
          "lastname varchar(30), "
          "age integer)");
Sign up to request clarification or add additional context in comments.

3 Comments

Oh I see, I didnot notice he is using different names, sorry. Hoever, I am having a problem using the same code, after hard-coded the path like this: QString path="c://Users//me//Document//workapce//myproject//databse.db" my app crashes. when debugging it just exit with crash .. what might be the problem
Is it possible to connect to a db file with a username and password?
@AttitudeMonger Try this open() method doc.qt.io/qt-5/qsqldatabase.html#open-1
2

His mistake was,

QDir databasePath;
QString path = databasePath.currentPath()+"/myDb.db"; // Not "myDb.db"
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(path);
db.open();
QSqlQuery query; // And he should insert some data, as the answer above mentioned
query.exec("create table person "
          "(id integer primary key, "
          "firstname varchar(20), "
          "lastname varchar(30), "
          "age integer)");

And the database file myDb.db is created in build directory not in his source code directory.

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.