Search code examples
c++qtqtsql

Parameter count mismatch in Qtsql


I'm trying to insert data into a QtSql database, but I keep getting the error:

"Parameter count mismatch"

What could be what I'm doing wrong?

#include <QtSql>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    qDebug() << QSqlDatabase::drivers();

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setHostName("LOCALHOST");
    db.setDatabaseName("people");
    db.setUserName("root");
    db.setPassword("");

    if(db.open()) {
        qDebug() << "Opened!";

        QSqlQuery query;

        query.prepare("INSERT INTO person (id, forename, surname) "
                      "VALUES (:id, :forename, :surname)");
        query.bindValue(":id", 1001);
        query.bindValue(":forename", "Bart");
        query.bindValue(":surname", "Simpson");
        query.exec();

        if( !query.exec() )
            qDebug() << query.lastError().text();
        else
            qDebug( "Inserted!" );

        db.close();

    } else {
        qDebug() << "Not opened";
    }
}

Solution

  • You don't have a table named person in the database. You are trying to insert values into a table that does not exist.


    I think that the error message is wrong. But anyway, I added a CREATE statement to your code, so that the table is created before the INSERT statement is executed:

    #include <QtSql>
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName(":memory:");
    
        if(!db.open()){
            qDebug() << "Not opened";
            return 1;
        }
        qDebug() << "Opened!";
    
        QSqlQuery query;
    
        //CREATE the table before executing the INSERT statement
        query.exec("CREATE TABLE person (id INTEGER, forename TEXT, surname TEXT);");
    
        query.prepare("INSERT INTO person (id, forename, surname) "
                      "VALUES (:id, :forename, :surname)");
        query.bindValue(":id", 1001);
        query.bindValue(":forename", "Bart");
        query.bindValue(":surname", "Simpson");
    
        if( !query.exec() )
            qDebug() << query.lastError().text();
        else
            qDebug( "Inserted!" );
    
        return 0;
    }
    

    This prints Inserted! now. But if I comment out the CREATE statement line I get the same error in your question:

    " Parameter count mismatch"