Getting database values into QStringList



  • In my qt c++ application I want to Query a database table and to insert the values into a QStringList!

    Following is my code!

    void Dialog::on_pushButton_clicked()
    {
    QStringList Names;
    if(QSqlDatabase::contains("MyConnection")){

            QSqlQuery qry(QSqlDatabase::database("MyConnection"));
          
    
            qry.prepare("Select NAME from User where NAME like '%Ab%' ");
           qry.exec();
            }
    

    }

    }

    The Query is executed successfully but I dont know how to get the NAME values into the QStringList! How can I achieve it?



  • @Lasith
    you can iterate over results with QSqlQuery::next() and get values with QSqlQuery::value().

    bool prepRet = query.prepare("Select NAME from User where NAME like '%Ab%' ");
    
    if (!prepRet) {
         qDebug() << query.lastError().text();
         return;
    }
    if (!query.exec()) {
         qDebug() << query.lastError().text();
        return;
    }
    QStringList list;
    while (query.next()) {
        list << query.value(0).toString();
    }
    

    EDIT: error reporting


  • Lifetime Qt Champion

    Hi,

    To add to @dream_captain, in case of an error, at least print the error string from the query so you know what went wrong.



Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.