【问题标题】:Insert or update if exists a QSQLITE database according to the row values in qt如果存在 QSQLITE 数据库,则根据 qt 中的行值插入或更新
【发布时间】:2018-01-20 19:32:31
【问题描述】:

在下面的代码中,我创建了一个表“one”,它是 QSQLITE 数据库的一部分,其属性如下面的代码所示。然后我将 QStrings a1,b1,c1,d1 插入到用户输入的表中。现在,只有当表中不存在 b1 和 c1 时,软件才必须插入数据库。如果表中存在 b1 和 c1,则必须将 d1 列值更新为已存在的 d1 值和新 d1 值的总和。

[例如:考虑,

(row1)“A B C D”(row2)“水果苹果红10”(row3)“水果香蕉黄15”

作为插入数据库的行。现在如果我必须插入另一行“fruit apple red 8”,它必须将表第一行的 D 列更新为 10+8 =“18”。 我该怎么做?

@   
QSqlQuery query;
    query.prepare("create table one (A varchar(20), B varchar(30), 
    C varchar(30), D integer(10))"); 
    query.exec();

    query.prepare("insert into one (A,B,C,D)" 
    "values(:a,:b,:c,:d)");
    query.bindValue(":a",a1);
    query.bindValue(":b",b1);
    query.bindValue(":c",c1);
    query.bindValue(":d",d1);
@

【问题讨论】:

    标签: c++ qt sqlite insert qt-creator


    【解决方案1】:

    尝试更新现有行。如果这不起作用,则该行不存在,您必须插入它:

    query.prepare("UPDATE one SET d1 = d1 + :d WHERE ...");
    query.bindValue(...);
    query.exec();
    if (query.numRowsAffected() == 0) {
        query.prepare("INSERT ...");
        query.bindValue(...);
        query.exec();
    }
    

    【讨论】:

    • 更新前如何检查“水果苹果红”是否已经存在?
    • UPDATE 已搜索此行。 numRowsAffected() 告诉你是否找到了这样的行。
    • query.prepare("UPDATE one SET d1 = d1 + :d WHERE A=:a, B=:b, C=:c"); query.bindValue(":a",a1); query.bindValue(":b",b1); query.bindValue(":c",c1);查询.exec(); @这个查询正确吗?
    猜你喜欢
    • 2016-01-14
    • 2014-05-05
    • 2015-12-17
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 2015-12-18
    • 1970-01-01
    相关资源
    最近更新 更多