Reputation: 9121
I'm having some troubles inserting values in my SQLite database
This is how I create the DB:
if(query.exec("CREATE TABLE IF NOT EXISTS visitorItemsV4 (channelID, itemId, itemName, itemPic, itemPrice, itemMeta);")) {
qDebug() << "Table `visitorItemsV4` created.";
}
And this is how I insert a new item:
if (db.isOpen()) {
qDebug() << itemId;
qDebug() << itemName;
qDebug() << itemPic;
qDebug() << itemPrice;
QSqlQuery query(db);
ret = query.exec(QString("insert or replace into visitorItemsV4 values ('%1', '%2', '%3', '%4', '%5', '%6');")
.arg(channel).arg(itemId).arg(itemName).arg(itemPic).arg(itemPrice).arg(itemPrice));
qDebug() << query.lastError();
if (ret) {
qDebug() << "saved item";
}
}
The problem is that the itemPrice
always gets the value of %5
and itemMeta
gets a value of %6
itemPrice
variable contains 499
so I would expect that to be the value of itemPrice
and itemMeta
.
Any ideas what I'm doing wrong?
Upvotes: 0
Views: 129
Reputation: 180060
Never try to create SQL commands by putting values directly into the string; this not only creates formatting problems, but allows SQL injection.
Use parameters instead:
query.prepare("insert or replace into visitorItemsV4 values (?,?,?,?,?,?)");
query.bindValue(0, channel);
query.bindValue(1, itemId);
query.bindValue(2, itemName);
query.bindValue(3, itemPic);
query.bindValue(4, itemPrice);
query.bindValue(5, itemPrice);
ret = query.exec();
Upvotes: 5