Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QSqlQuery A fail after QSqlQuery B exec an invalid SQL



  • Hi and thank you in advance

    I'm running in a while(query.next()) and QString name = query.value("name").toString() return the current value, but if another query fail inside the while loop the query.value("name").toString() has problems.

    The table is:
    CREATE TABLE a (
    id INT(11) NOT NULL AUTO_INCREMENT,
    name VARCHAR(50) NULL DEFAULT NULL,
    description VARCHAR(50) NULL DEFAULT NULL,
    PRIMARY KEY (id)
    )

    with a few rows.

    I'm compiling in windows with msvc2017 and also mingw, same results.
    I'm using Qt 12.2.2 32 bits
    I wrote this simple program to demostrate my problem.

    #include <QCoreApplication>
    #include <QSqlDatabase>
    #include <QSqlQuery>
    #include <QSqlError>
    #include <QVariant>

    int main(int argc, char *argv[])
    {
    // QCoreApplication a(argc, argv);

    QSqlDatabase db;
    
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setDatabaseName("simple");
    db.setHostName("127.0.0.1");
    db.setPort(3306);
    db.setUserName("root");
    db.setPassword("password");
    
    db.open();
    
    if(!db.isOpen())
    {
        return 1;
    }
    
    QString sql, sql2;
    QSqlQuery query, query2;
    
    sql = "select * from a;";
    
    if(!query.exec(sql))
    {
        return 1;
    }
    
    while(query.next())
    {
        // first time return the value, second time print unknown field name
        QString name = query.value("name").toString();
        QString description = query.value("description").toString();
    
        sql2 = "sql with error;";
    
        if(!query2.exec(sql2))
        {
            continue;
        }
    }
    

    // return a.exec();
    }


  • Lifetime Qt Champion

    You example does not compile and where exactly happens the problem then? What SQL database do you use?



  • @mmiacca
    You have a "nested" second QSqlQuery. I do not know if that is supposed to work, or maybe it depends on the driver --- I can imagine issues with this --- but https://stackoverflow.com/questions/42978239/qt-nested-qsqlquery-not-working reports the same as you. And got no solution.

    If you continue to have problems with this, the usual would be to let the first query exhaust all its next()s so it is finished, save up what you need from it (name, description, whatever) into a vector/list/similar, and use that to generate the second QSqlQuerys outside of that loop. Or, write a cleverer SQL statement (like a JOIN) to achieve whatever you are trying to get here. It's not great "form" to be trying to run a new query each time round another query.


Log in to reply