1

我想在 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 功能?

4

1 回答 1

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 
           + ")"
           ));
于 2012-09-28T12:31:28.427 回答