0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
INdek
  • 107
  • 3
  • 5
  • `QSqlQuery` doesn't take the constructor argument to execute it as sql query, to execute sql query use `exec()` method, to see the latest error use `lastError().text()`. Post the message content of `QMessageBox::information(NULL,"Query executed","The querry returned: " + data.lastError().text());` – SIFE Mar 22 '13 at 02:02
  • it returns empty, i have tried to use this code `data.prepare("insert query here"); data.exec(); data.first(); QString result = data.value(0).toString()` and it the result var is = 0 – INdek Mar 22 '13 at 09:12
  • I also tried to execute `qDebug() << data.lastError();` and it outputed QSqlError(-1, "", ""), wich by my google-fu is that the query executed correctly – INdek Mar 22 '13 at 09:28

2 Answers2

0
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);
}
Amartel
  • 4,248
  • 2
  • 15
  • 21
-1

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.

  • 1
    You didn't solve the issues in the OP's question. Your codes might work(even not show up your codes), but why the OPs codes not working? – Sphinx Mar 06 '18 at 17:24