how to select where xxx=? sqlite c++



  • Hi,

    I used sqlite query in js and all is working but in c++ I can't do same, could you help?

    In js:

    function dbRead(yyyy)
    {
        var db = dbGetHandle()
        db.transaction ( function (tx) {
            var results = tx.executeSql(
    'SELECT * FROM table WHERE columnx = ?', [yyyy] )
       })
    }
    

    in cpp I have:

            QSqlQuery query;
            query.exec("SELECT * FROM table WHERE columnx = 'yyyy' " );
    

    how can I replace 'yyyy' by variable string in C++?

    thank you very much for your help

    Philippe



  • @filipdns
    See http://doc.qt.io/qt-5/sql-sqlstatements.html, e.g.

        QSqlQuery query;
        query.prepare("INSERT INTO employee (id, name, salary) "
                      "VALUES (?, ?, ?)");
        query.addBindValue(1001);
        query.addBindValue("Thad Beaumont");
        query.addBindValue(65000);
        query.exec();
    

    So prepare(), addBindValue(), exec().



  • @JonB Hi, thanks a lot

    here the working query:

            query.prepare("SELECT * FROM table WHERE columnx =\""+yyyy+"\"");
            query.exec();
    

    thank you for your help!!



  • @filipdns
    What you have done is very different. You have not used parameters as you seemed to ask for and as my answer gave you, instead you have chosen to expand the variable into the literal text of the SQL query.

    Apart from the fact that this may be (slightly) "inefficient", and that the way you have written it may as well not bother with prepare() but just do the exec() instead, your code will go wrong if the variable has any "unusual" characters in it, e.g. try it when yyyy variable itself includes a " (double-quote) character (whereas your JS tx.executeSql would work correctly).

    I suggest that you heed the code I gave to use addBindValue(), but it's up to you....



  • @JonB Hello, you are right, I used your solution, It will be much better.

            QSqlQuery query;
            query.prepare("SELECT * FROM table WHERE columnx =?");
            query.addBindValue(yyyy);
            query.exec();
    

    thank you very much!!!


Log in to reply
 

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