4

The following code creates a table and stuffs the database with data. When running the below code, I receive an error 'Parameter count mismatch' on query.exec(). However, if I use the commented line instead, everything works fine. How am I misusing the prepare feature?

QSqlQuery query;
if (query.exec("CREATE TABLE Users ( u_ID INT IDENTITY(1,1) PRIMARY KEY, cName varchar(25) UNIQUE )"))
{
    for (int i=1;i<=100;++i)
    {
        QString uName;
        uName = "user" + QString::number(i);
        query.prepare("INSERT INTO Users (cName) VALUES(':UNAME')");
        query.bindValue(":UNAME",uName);
        query.exec();
        //query.exec("INSERT INTO Users (cName) VALUES('"  + uName +  "')");
        if (query.lastError().isValid()){
            QMessageBox::information(0,"ERR!",query.lastError().text());
        }
    }
}

1 Answer 1

6

Just use:

query.prepare("INSERT INTO Users (cName) VALUES(:UNAME)");

i.e. don't quote bind variables.

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

3 Comments

+1 : The ' around strings, strings escaping, and all other type considerations are all dealt with for you in parameterised queries.
So, using prepare is safe for 'raw' user-data?
Yes, if you use bind variables as you do here.

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.