使用Sql仅将选定的值插入SQLite表中

时间:2012-09-28 12:08:05

标签: c++ sqlite qt

我想在SQLite表中插入一些值。

查询是:

insert into TableName (field1,field2,field3) values (field1val, field2val, field3val)

假设该表有20个字段。我想根据用户输入的值选择应插入哪个字段。其余的字段应该没有价值。

我目前的解决方案是:

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)

有没有更好的方法呢?也许有些QSql功能?

1 个答案:

答案 0 :(得分:1)

我会在地图中保存名称和值,并在一个循环中构建查询:

//You hold the field names and the corresponding values here.
//The map's key is the field name, the map's value is the value. 
QVariantMap pairs;
//this will hold the values to compare with to decide whether to print the value
//or not
QVariantList compareWithMe;

QString fieldNames;
QString fieldValues;

int count = 0;
QVariantMap::iterator it = pairs.begin();
for( it; it != pairs.end(); it++ )
{
    if( it.value().toInt() == compareWithMe[count] )
    {
        count++;
        continue;
    }
    fieldNames.append( it.key() );
    fieldValues.append( it.value().toString() );
    //fieldValues.append( QString("%1").arg(it.value()) ); if you like it this way. 
    count++;
}

//Note that I've placed the opening and closing braces here, 
//saving you two lines of code:
//fieldNames.append(")");
//fieldValues.append(")");
query.exec(QString(
           "INSERT INTO TableName (" 
           + fieldNames 
           + ") VALUES (" 
           + fieldValues 
           + ")"
           ));