QSqlQuery bindValue not working



  • I am trying to use a query with parameters on Qt 5.5.1 and a SQLite Database. I can insert records without using parameters, but when I try and use parameters, I get a "parameter count mismatch".

    I have tried all of the suggestions, I have found online. None have worked. My next step is to pull down the source for the SQLite Driver.

    Any thoughts?

    @

    QString sql;
    QString filename = "c:\\scratch\\people.db";
    
    QFile::remove(filename);
    
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(filename);
    if (!db.open())
    {
        qDebug() << db.lastError().text();
        return;
    }
    
    QSqlQuery q0;
    
    sql = "CREATE TABLE People ("
          "PersonId INTEGER PRIMARY KEY,"
          "Name VARCHAR(100)"
          ")";
    q0.exec(sql);
    
    QSqlQuery q1;
    
    sql = "INSERT INTO People (Name) VALUES ('Bob')";
    
    if (!q1.exec(sql))
    {
        qDebug() << q1.lastError().text();
    }
    
    QSqlQuery q2;
    
    sql = "INSERT INTO People (Name) VALUES (:a)";
    
    if (!q2.prepare(sql))
    {
        qDebug() << "Unable to prepare";
    }
    
    q2.bindValue(":a", "Dan");
    
    if (!q2.exec(sql))
    {
        QString msg;
    
        msg = "'" + q2.lastError().text() + "' when executing '"
                + q2.executedQuery() + "'";
        qDebug() << msg;
    }
    

    @



  • I found the problem. If the SQL statement is passed to the query in the prepare statement, it should not be passed in the exec statement, The line

      if (!q2.exec(sql))
    

    should be

      if (!q2.exec()))

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.