1

Here is my code, there doesn't seem to be anything wrong:

QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("thedata.sqlite");
db.open();

QSqlQuery query;
query.prepare("SELECT lastname FROM people where firstname='?' ");
query.bindValue(0, lineEdit->text());

bool x = query.exec();

if(x){
   lineEdit_2->setText(query.value(0).toString());
 }

 else {
   QSqlError err;
    err = query.lastError();
    QMessageBox::about(this,"error",err.text()   );
 }

When the program is working always it gives the error parameter count mismatch I'm using qt 4.8 and its own headers for using sqlite.

I would be very thankful for any advice, though I searched in google i see many posts in this issue but nothing helped me.

Thank you.

2
  • Have you verified that lineEdit->text() actually returns something, preferably a string? Commented Dec 18, 2012 at 16:29
  • @TimoGeusch yes its sure, I type the first name their. Commented Dec 18, 2012 at 16:31

1 Answer 1

2

You're prepared statement is wrong, it should be:

quary.prepare("SELECT lastname FROM people where firstname=?");

Notice that there are no single quotes (') around the placeholder. If you put the quotes, it gets passed as a literal to the database, leaving you with a parameter-less query and code that passes too many parameters.

(Changing that variable name to query would be a nice touch too.)

Also you need to check the return value if QSqlQuery::prepare, and print out/display the error message you're getting from that if it fails – otherwise QSqlQuery::exec resets the current error and you'll get a pretty meaningless error message if there was a problem parsing the prepared statement.

if(x){
  lineEdit_2->setText(quary.value(0).toString());
}

This is incorrect too. The you need to call (and check the return value of) query.next() to position the result set to the first row returned (if there is one). You can't use .value(X) before you've called .next().

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

3 Comments

now it didn't give eny error but nothing happens. it dont display the lastname in lineEdit_2
That's a different problem. You need to advance the result set to the first row with query.next(), otherwise query isn't positioned on a row.
ok accepted as answer. thank you very mutch, I would have never found this alone, I was trying to solve this for hours. thanks again... :)

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.