Problem is that when I exec sql insert query (I’m using Qt Creator and sqlite), two new rows are added into database instead of one.
Here’s code block
void MainWindow::on_insertButton_clicked(){
db.open();
QString name = ui->nameLineEdit->text();
QString queryString = "INSERT INTO highscores (name, score) VALUES '%1',%2";
QSqlQuery query(queryString.arg(name).arg(score));
query.exec();
}
This code should insert values name and score into database just once but after query exec two same rows are inserted.
Anyone has an idea what’s the problem?
Isntead of
you should write
SQL’s
INSERTcommand expects a list of datasets afterVALUESseparated by commas, each of them in parentheses with their column values.The following command inserts one tuple into the table
table:Because you didn’t put the two values in parentheses you asked SQLite to insert two datasets with one value each:
(The funny thing is that I tested this with both my SQLite and MySQL installations. They both threw an error when I omitted the parentheses at all. But this may depend on the version and some options you are using.)
Please never use
QString::argto fill in arguments of a SQL query!(Or any other method of string building, like concatenation.) This can lead to a possible SQL injection.
In order to build statements with variable arguments you should use SQL prepared statements as provided by QSqlQuery bound values:
Note that I did not quote the string argument in the prepared statement.