简体   繁体   中英

How can I insert a random number of values in different columns? querys. C++. SQlite database

In my database, I have a table called "history" with 3 columns (distance1, distance2, distance3)

I will simplify what I have in my code:

I have a vector "Ldist" that each time has different amount of distances. Sometimes 1 distance, or 2, or 3. Normally I know how much distances it will have, and I work like this:

(example: if I know that the vector will have 2 distances)

QSqlQuery qry;
qry.prepare("INSERT INTO history (distance1, distance2) "
        "VALUES (:placeholder0, :placeholder1)");
qry.bindValue(":placeholder0", Ldist.at(0));
qry.bindValue(":placeholder1", Ldist.at(1));
qry.exec();

My problem comes when I don't know how many distances this vector will have. How can I make the "columns affectec" and the "placeholders needed" available to work with the random amount of values in the vector "Ldist"?

I tried to make a loop, but I don't know how to change my code to adapt to what I need.

Thanks in advice.

You're right that a loop is needed. Something like this (untested)

if (!Ldist.empty())
{
    QString columns, values;

    for (size_t i = 0; i < std::min(3, Ldist.size()); ++i)
    {
        columns += QString("distance%1,").arg(i + 1);
        values += QString(":placeholder%1,").arg(i);
    }

    // trim trailing comma
    columns.remove(columns.length() - 1, 1);
    values.remove(values.length() - 1, 1);

    QString queryStr = QString("INSERT INTO history (%1) VALUES (%2)").arg(columns, values);

    QSqlQuery qry(queryStr);

    for (size_t i = 0; i < std::min(3, Ldist.size()); ++i)
    {
        QString placeHolder = QString(":placeholder%1,").arg(i);
        qry.bindValue(placeHolder, Ldist.at(i));
    }

    qry.exec();
}

Thanks acraig5075!! <3

I have learnt that you can use placeholders also for the columns. I didn't know that. Much easier if we know that ^^

This is how I have let my code:

QString column; QSqlQuery qry;

for (c=0; c < Ldist.size(); c++)
{  
     column = QString("dist%1").arg(c+1);    

     qry.prepare("INSERT INTO history (:placeholder0) VALUES (:placeholder1)");
     qry.bindValue(":placeholder0",column);
     qry.bindValue(":placeholder1",Ldist.at(c));
     qry.exec();
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM