July 10, 2010

joseph.s joseph.s
Lab Rat
1 posts

Using QSqlQuery bindValue()

 

Hi,

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.     }
  11.  
  12.     query.bindValue("username", username);
  13.  
  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?

Thanks!

3 replies

July 10, 2010

Tobias Hunger Tobias Hunger
Mad Scientist
3383 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
6295 posts

Also, I think that you should do:

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

That is, include the colon in the binding code.

 Signature 

Looking for Qt developers to join our team @ i-Optics: https://qt-project.org/forums/viewthread/25393/

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!