我有一个 SQLite 数据库,我创建了一个像这样的唯一索引:
CREATE UNIQUE INDEX [my_unique_idx] ON [my_table] ([field1], [field2]);
现在在我的程序中,我想在 my_table
中INSERT OR REPLACE
一行,如果它被插入,我需要在另一个“从”表中插入其他行。另一方面,如果该行已更新,我什么都不用做。换句话说:
if ( query.exec(
"insert or replace into my_unique_idx"
" (field1, field2, other_field)"
" values"
" (1, 2, 'foo')"
) )
{
if ( query.is_was_really_inserted() ) // <---- how to ?
{
slave_query.exec( "insert into slave_table......
}
}
我知道,我可以通过几个查询来做到这一点:选择一个具有适当值的行,如果该行不存在,则将数据插入两个表(“master”和“slave”),然后更新“master”表如果行存在。
但这使得唯一索引和 INSERT OR REPLACE
子句变得毫无意义。
最佳答案
这似乎可以通过触发器实现。 SQLite documentation状态:
When a UNIQUE or PRIMARY KEY constraint violation occurs, the REPLACE algorithm deletes pre-existing rows that are causing the constraint violation prior to inserting or updating the current row and the command continues executing normally.
[...]
When the REPLACE conflict resolution strategy deletes rows in order to satisfy a constraint, delete triggers fire if and only if recursive triggers are enabled.
因此,如果您有一个删除触发器,您将知道是否有任何行被删除以替换它。
您可以:
使用该触发器来更新一些中间表,然后在您的查询之后运行另一个查询来检查哪些行已被更新(似乎是最糟糕的解决方案)。
使用该触发器来确保您的数据库一致性(不错,但是代码和脚本之间会有一些逻辑碎片)。
使用 Qt 注册触发器将调用的数据库事件:参见 this answer .似乎 SQLite supports event notifications .
关于c++ - 如何检查行是否在 SQLite 中被插入或替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32502839/