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