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!

6 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
6397 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”.

August 21, 2014

arsinte_andrei arsinte_andr..
Hobby Entomologist
126 posts

Can you edit your first post Please in order to let other know that this problem was Solved. Just Add [SOLVED] in front of the main title

August 21, 2014

Andre Andre
Robot Herder
6397 posts
arsinte_andrei wrote:
Can you edit your first post Please in order to let other know that this problem was Solved. Just Add [SOLVED] in front of the main title

Why do you kick the topic alive again after more than four years just to add that off-topic comment?

August 21, 2014

arsinte_andrei arsinte_andr..
Hobby Entomologist
126 posts

sorry it was my fault – I’ve been searching for something and I did not realise the date… I was ready to answer to this problem because Ihad even myself some trouble with bindValue when I’ve realised that it was already answered ( please note that I did not look at the date – but is a good lesson for me – it will never repeat again sorry )

 
  ‹‹ 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!