1

So part of the purpose of using (and reusing) prepared statements is that the database driver performs less work. Coming from Perl, I am used to preparing a SQL query and storing a reference to that prepared query so that I can later bind some values and execute the query, many times if necessary.

With Qt C++ (Qt 5.1) I try to do this:

    class MyClass {
            [...]
            QSqlDatabase db;
            QSqlQuery insert_query;
    };

    MyClass::MyClass() {
            db = QSqlDatabase::addDatabase("QSQLITE");
            db.setDatabaseName("whatever");
            db.open();

            insert_query = QSqlQuery(db);
            insert_query.prepare("insert into players (firstname, lastname) values(:firstname, :lastname)"));
    }

    void MyClass::MyMeth(QString firstname, QString lastname) {
            insert_query.bindValue(":firstname", firstname); //COMPILE ERROR
    }

error: no matching member function for call to 'bindValue'

note: candidate function not viable: 'this' argument has type 'const QSqlQuery', but method is not marked const

But I want to bind new values in the prepared query outside of the MyClass constructor. I found this, but I am suspicious that it is cargo-cult because calling QSqlQuery::prepare("query") more than once is effectively a noop if "query" remains the same (even if the QSqlQuery object is different). Is this true with some drivers? Otherwise, what am I missing? How am I supposed to reuse prepared queries?

1 Answer 1

3

Your compiler error has nothing to do with the re-usedfulness of QSqlQuery. Did you declare MyMeth as const? Remove the const, it's preventing call to the non-const bindValue().

Change

void MyMeth(QString firstname, QString lastname) const;

to

void MyMeth(QString firstname, QString lastname);
Sign up to request clarification or add additional context in comments.

1 Comment

Bingo! I missed this because I forgot I was in an overridden method with const inherited. I need bind the values in another method I control the signature of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.