I want to insert some values into an SQLite table.
The query is:
insert into TableName (field1,field2,field3) values (field1val, field2val, field3val)
Let’s say the table has 20 fields. I want to choose which field should be inserted depending on this value which is user input. The rest of fields should have no value.
My current solution is:
QString valuesToInsertFieldNames("(");
QString valuesToInsert("(");
if(field1val != -1)
{
valuesToInsertFieldNames+= "field1";
valuesToInsert += QString("%1 ").arg(field1val);
}
if(field2val != -1)
{
valuesToInsertFieldNames+= "field2";
valuesToInsert += QString("%1").arg(field2val);
}
...
valuesToInsertFieldNames+= ")";
valuesToInsert += ")";
query.exec(QString("insert into TableName " + valuesToInsertFieldNames +
"values" + valuesToInsert)
Is there some better way of doing it? Maybe some QSql functionality?
I would hold the names and values in a map, and construct the query in a cycle: