4

The following code fails on QSqlQuery::exec(). When I run the query without the prepared statement argument, it returns the correct results, available as one would expect through QSqlQuery::next()

executedQuery() reports that ":username" was in fact not replaced by the argument, but with a ? (Is it supposed to, since the query did not execute successfully?).

db_ is a QSqlDatabase class variable and isOpen() reports true. The Qt framework verison is 4.7.3.

DBSql::userInfo(const QString &username, 
                QString &passwd, 
                QString &name, 
                UserPriv priv)
{
  QSqlQuery userQuery(db_);
  const QString userStr("SELECT u.id, u.fullname, u.password, p.description \
                        FROM users u INNER JOIN privilege p ON u.privilege_id = p.id \
                      WHERE u.username = :username");
  userQuery.bindValue(":username", username);

  if (!userQuery.prepare(userStr))
    std::cout << "prepare failed" << std::endl;

  if (userQuery.exec()) {
    while (userQuery.next()) {
      userId = userQuery.value(0).toInt();
      name = userQuery.value(1).toString();
      passwd = userQuery.value(2).toString();
      const QString privilegeDesc = userQuery.value(3).toString();
    }
  }
}
3
  • 3
    try to call the prepare method before binding value Commented Nov 9, 2012 at 10:43
  • You are leaking your QSqlQuery resource. You should probably use a simple automatic variable : QSqlQuery userQuery(db_); Commented Nov 9, 2012 at 14:10
  • Edited, and thanks. It was originally not written with heap allocation, but I tried that as a sort of desperate last resort to see if the behaviour changed. Commented Nov 9, 2012 at 14:33

1 Answer 1

7

You have to call userQuery->prepare(userStr) before userQuery->bindValue(":username", username)

Sign up to request clarification or add additional context in comments.

1 Comment

You are correct, sir. Confirmed. :) How do I upvote your answer? It says i need 15 reputation to do so.

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.