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

QT SQL query loop?



  • Hey, currently this loop only gets the first username in the table, how can i properly do this so it checks all rows for the username
    while (query.next() && query.value("Username").toString().toUtf8().constData() && query.value("Password").toString().toUtf8().constData())
    {
    printf("Usernames: %s", query.value("Username").toString().toUtf8().constData());


  • Lifetime Qt Champion

    Hi,

    How many entries do you have in that table ?
    What query did you use ?
    Why are you doing this complex check in the while condition ?



  • Hello, I have 5 entries
    query.exec("SELECT * FROM users");
    if (query.size() > 0)

    and its the only check i could think of



  • @davethedave

    query.exec("SELECT * FROM users");
    while (query.next())
    {
        printf("Usernames: %s", query.value("Username").toString());
    }
    


  • @JonB
    Prints first entry in the table still.



  • @davethedave
    Please show output of each of the 2 following:

    query.exec("SELECT COUNT(*) FROM users");
    while (query.next())
    {
        printf("Number: %s\n", query.value(0).toString());
    }
    
    query.exec("SELECT * FROM users");
    while (query.next())
    {
        printf("Username: %s\n", query.value(0).toString());
    }
    


  • @JonB said in QT SQL query loop?:

    query.exec("SELECT * FROM users");

    from the first:
    http://prntscr.com/khp72u

    if i append
    .toUtf8().constData() then the below
    http://prntscr.com/khp79y

    from the second:
    http://prntscr.com/khp72u

    if i append
    .toUtf8().constData() then the below
    http://prntscr.com/khp7tw

    Also there is only 3 rows now



  • @davethedave
    Firstly, I don't work in C++ so I don't test the code for the right way to pass the output string to printf(). So your corrections are good. [BTW you'd be better off not using printf() and using Qt/C++ functions, then you wouldn't have all that toUtf8().constData() stuff, but that's another matter.]

    As you can see you have 3 rows matching the query, you tell us you have 5, or you had 5 and now you have 3. That's worrying when you're asking for help. Your Username value appears to be 1 from the output. That is a strange username. I don't know what your problem is. The original code should correctly print out whatever is in the Username column of each row encountered (note that since you didn't put a \n in it will all come on one line, which isn't great, I do trust that is not what this is all about.)


Log in to reply