danial weaber
danial weaber

Reputation: 876

Using sqlite database with qt

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.

Upvotes: 1

Views: 1320

Answers (1)

Mat
Mat

Reputation: 206869

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().

Upvotes: 2

Related Questions