Search code examples
c++mysqldatabaseqtqsqlquery

Can't execute mysql querys with QT


I'm trying to connect and execute a query with the QT framework, I can connect to the mysql db and I have tested the query and verified it works on the database. I think the mysql driver is correctly installed because I can connect and it doesn't throw any errors

void Login::on_loginButton_clicked()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("127.0.0.1"); 
    db.setDatabaseName("TestBase");
    db.setUserName("username");
    db.setPassword("password");
    if (!db.open()) {
    QMessageBox::critical(0,"Database Error","Could not connect to the database, check your internet connection.");
    }


QSqlQuery data("SELECT * FROM `TestBase`.`Users` WHERE `userName` = 'Afonso'");
//data.exec("SELECT * FROM `TestBase`.`Users` WHERE `userName` = 'Afonso'");
QMessageBox::information(NULL, "Query executed", "The query returned: " + data.exec());
}

I have also tried with

data.exec("insert query here");
data.next();

Nothing seems to work

I am trying to display the result of the query in a QMessageBox


Solution

  • QSqlQuery query(db);
    query.prepare("SELECT * FROM `TestBase`.`Users` WHERE `userName` = :user_name");
    query.bindValue(":user_name", "Afonso");
    if (!query.exec())
    {
        qDebug() << query.lastError().text();
        retrun;
    }
    while (query.next())
    {
        QVariant v = query.value(0);
    }