July 10, 2010

joseph.s joseph.s
Lab Rat
1 posts

Using QSqlQuery bindValue()



I’ve just started using Qt 4.6. I have the following code:

  1. User *UserMapper::getByUsername(QString username)
  2. {
  3.     // Get user from database.
  4.     QString sql = "select username, password from users "
  5.                   "where username = :username";
  6.     QSqlQuery query;
  7.     if (false == query.prepare(sql)) {
  8.         qDebug("Failed to prepare query.");
  9.         return 0;
  10.     }
  12.     query.bindValue("username", username);
  14. ...
  15. }

However, it does not compile:

error C2664: ‘void QSqlQuery::bindValue(const QString &,const QVariant &,QSql::ParamType)’ : cannot convert parameter 2 from ‘QString’ to ‘const QVariant &’

I must be missing something very obvious. Do I have to manually convert the QString to QVariant? How do I do that?


3 replies

July 10, 2010

Tobias Hunger Tobias Hunger
Robot Herder
3387 posts

Have you tried using “QVariant(username)” instead of using “username” directly? The conversion should actually happen implicitly… maybe you forgot to include the QVariant header?

July 10, 2010

Andre Andre
Robot Herder
6393 posts

Also, I think that you should do:

  1. query.bindValue(":username", username);

That is, include the colon in the binding code.

July 10, 2010

joseph.s joseph.s
Lab Rat
1 posts

Thank you very much for the help! You are both correct. I actually did forget to include the QVariant header, and it is supposed to be “:username” instead of “username”.

  ‹‹ Undefined DESTDIR_TARGET and other variables in Mac OSX      How can I style a QToolBar extension button icon via CSS ››

You must log in to post a reply. Not a member yet? Register here!