1

I am having trouble connecting to my sqlite database using my qt application. I have a helper class DBManager that is supposed to have functions to open and close the database, as I would like to reuse the code in multiple places. Here is the dbmanager.cpp

DBManager::DBManager()
{

}
void DBManager::connOpen()
{

    path = QCoreApplication::applicationDirPath() + "/GameSuitedb.db";
    mydb=QSqlDatabase::addDatabase("QSQLITE");
    mydb.setDatabaseName(path);

void DBManager::connClose() /*Closes connection and commits changes to database*/
{
    mydb.close();
    mydb.removeDatabase(QSqlDatabase::defaultConnection);
}

Note my database is named GameSuitedb and is located next to the executable And here is where I am trying to access my database:

void CreateUser::on_pushButton_submit_clicked()
{
    dbmanager.connOpen();
    QString username = ui->lineEdit_username->text();
    QString password = ui->lineEdit_password->text(); //Gets password text
    QSqlQuery qry(dbmanager.mydb);
    qry.prepare("INSERT INTO users (username,password) VALUES ('"+username+"', '"+password+"')");

    if(qry.exec()){
    }
    else{
        ui->statusbar->showMessage(qry.lastError().text());
    }
        dbmanager.connClose();
}

The error the above code gives me when launched is QSqlQuery::prepare: database not open.

2
  • Have you verified in your debugger than the path variable is what you think it is? Also, read up on how to use prepared queries -- your current code contains an obvious opportunity for SQL injection attacks.
    – MrEricSir
    Mar 8, 2017 at 23:14
  • The sqlite support in qt will at least try to create a new db if the database file does not exist in the folder.
    – drescherjm
    Mar 8, 2017 at 23:16

1 Answer 1

5

The error code tells you that the database is not open because your DBManager::connOpen() function seems to be doing everything except actually opening the database, contrary to how it's named.

You need to call QSqlDatabase::open() at the end of DBManager::connOpen() function so that the database gets opened and will be made ready for use.

void DBManager::connOpen()
{
    path = QCoreApplication::applicationDirPath() + "/GameSuitedb.db";
    mydb=QSqlDatabase::addDatabase("QSQLITE");
    mydb.setDatabaseName(path);
    if(!mydb.open())
    {
        //use lastError() here to figure out what went wrong.  
    }
}
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.