Question

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

Was it helpful?

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);
}

OTHER TIPS

I use pyqt but in general with a select query, I start to get data with .first() rather than .exec() .exec_() in pyqt. After that next() works just fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top