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 に答える