[Solved]Insert and modify the database at once



  • @
    void komicaDB::add_message_number(std::map<QString, int> const &data) const
    {
    QSqlQuery qry;
    qry.prepare("INSERT INTO komica_data (address, number) VALUES (?, ?)");

    std::for_each(std::begin(data), std::end(data), [&](std::pair<QString, int> const &value)
    {
      qry.addBindValue(value.first);
      qry.addBindValue(value.second);
      qry.exec&#40;&#41;;
    }&#41;;   
    

    }
    @

    @
    void komicaDB::update_message_number(std::map<QString, int> const &data) const
    {
    QSqlQuery qry;

    qry.prepare("UPDATE komica_data SET number = ? WHERE address = ?");
    std::for_each(std::begin(data), std::end(data), [&](std::pair<QString, int> const &value)
    {
      qry.addBindValue(value.second);
      qry.addBindValue(value.first);
      qry.exec&#40;&#41;;
    }&#41;;    
    

    }
    @

    I could update and add the data into the table separately, what if I like to
    update and insert the data into the table simultaneous?

    assume the data of the table are
    Original table :
    address number
    one 1
    two 2
    three 3

    the data of the std::map are
    address number
    one 100
    two 200
    three 300
    four 400

    now I would like to synchronous the data of the database and the std::map
    Currently I do like this
    @
    add_message_number(data);
    update_message_number(data);
    @

    Do I have a better choice?Thanks



  • If I have understood you correctly (you want to insert data into the table, and if the data already exists it should be updated) you can use non-standard <code>REPLACE INTO</code> (at least if you are on MySQL or SQLite, there might be a similar command in other DBMSs).



  • Thanks, I study SQL from W3C but haven't find out there are something like "REPLACE INTO"
    Maybe it is because this is a non-standard instruction?



  • Yes, this is a non-standard extension specific to some DBMSs.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.