A. Shears
A. Shears

Reputation: 115

Connect to SQLite database using qt

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.

Upvotes: 1

Views: 2714

Answers (1)

Vada Poché
Vada Poché

Reputation: 780

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.  
    }
}

Upvotes: 5

Related Questions