Sebastian Bartos
Sebastian Bartos

Reputation: 2497

QSqlQuery with SQLite database: prepare + bindValue not updating table

I'm having trouble with QSqlQuery: it's not updating my SQLite database.

I initialize the database like this (which works fine):

myDB = QSqlDatabase::addDatabase("QSQLITE");
myDB.setDatabaseName(QDir::homePath() + QDir::separator() + "file.db");
myDB.open();

if(!myDB.tables().contains("presets")) {
    myDB.exec("CREATE TABLE presets (id INTEGER PRIMARY KEY ASC, path TEXT);");
    for (int i=0; i<10; i++)
        myDB.exec("INSERT INTO presets (path) VALUES ('n/a')");
}

I have a QString array of values that I want to update into there.

QString presets[10];
preset[0] = "foo";
preset[1] = "bar";
...

I try to update the database with a for loop like this:

QSqlQuery qPreset(myDB);
qPreset.prepare("UPDATE presets SET path=':path' WHERE id=':id';");
for (int i=0; i<10; i++){
    qPreset.bindValue(":path", presets[i]);
    qPreset.bindValue(":id", i+1);
    qPreset.exec();
}

But nothing happens in the database and I don't get any error messages either. Any ideas why?

Edit:

This (ugly as it is) works perfectly fine though, so it's not the connection:

for (int i=0; i<10; i++)
    myDB.exec("UPDATE presets SET path='" + presets[i] + "' WHERE id='" + QString::number(i+1) + "';");

Upvotes: 0

Views: 4040

Answers (1)

Sebastian Bartos
Sebastian Bartos

Reputation: 2497

Based on the question from @Nejat I have figured out the answer: I had to remove all the single quotes. I failed to notice that QSqlQuery::bindValue() takes care of all the quoting that's necessary.

Working snippet:

qPreset.prepare("UPDATE presets SET path=:path WHERE id=:id;");

Thanks for the hint.

Upvotes: 6

Related Questions