如何在 SQLite3 中使用 Qt QSqlDriver::subscribeToNotification? [英] How to use Qt QSqlDriver::subscribeToNotification with SQLite3?

查看:65
本文介绍了如何在 SQLite3 中使用 Qt QSqlDriver::subscribeToNotification?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Qt 应用程序,其中不同的模型可以插入/删除/更新同一个表.当一个模型更改数据库时,我希望其他模型收到更改通知,以便他们可以相应地更新视图.

I'm writing a Qt application where different models can insert/delete/update the same table. When one model changes the database, I would like the other models to be notified of the change, so they can update their views accordingly.

似乎在 SQLite 中监视插入、删除和更新的最佳方法是使用 QSqlDriver::subscribeToNotification 然后对通知信号做出反应.我知道语法是这样的:

It seems that the best way to monitor inserts, deletes and updates in SQLite is to use QSqlDriver::subscribeToNotification and then react to the notification signal. I know the syntax is along the lines of:

db.driver()->subscribeToNotification("anEventId");

但是,我不确定 anEventId 是什么意思.anEventId 是 SQLite 提供的常量,还是我使用触发器或其他方式将这些特定事件编码到 SQLite 中,然后订阅它们?

However, I'm not sure what anEventId means. Is anEventId a constant provided by SQLite or do I code these specific events into SQLite using triggers or something else and then subscribe to them?

推荐答案

Qt sqlite 驱动程序中的 subscribeToNotification 实现依赖于 sqlite3_update_hook sqlite C API 的函数.然而,Qt 驱动程序不转发执行的操作,只是转发表名,这应该是传递给 subscribeToNotificationanEventId 参数>.简而言之,您可以监听任何表中发生的事件(假设它是一个 rowid 表,但是它通常是)将表名传递给 subscribeToNotification 方法.但是,当您的插槽捕获 notification 信号时,您只知道该表中发生了一个操作,但(遗憾的是)Qt 不会告诉您是哪一个(INSERT、UPDATE 或 DELETE).

The subscribeToNotification implementation in the Qt sqlite driver relies upon the sqlite3_update_hook function of the sqlite C API. The Qt driver, however, is not forwarding the operation performed, just the table name, and that should be the misterious anEventId argument to pass to subscribeToNotification. In short, you can listen to events occurring in any table (given it is a rowid table, but it generally is) passing the table name to the subscribeToNotificationmethod. When your slot catches the notification signal, though, you only know that an operation occurred in that table, but (sadly) Qt won't tell you which one (INSERT, UPDATE, or DELETE).

所以,给定一个QSqlDriver * driver:

driver->subscribeToNotification("mytable1");
driver->subscribeToNotification("mytable2");
driver->subscribeToNotification("mytable3");

然后在您的插槽中:

void MyClass::notificationSlot(const QString &name)
{
    if(name == "mytable1")
    {
        // do something
    }
    else if(name == "mytable2")
    {

    //etc...

这篇关于如何在 SQLite3 中使用 Qt QSqlDriver::subscribeToNotification?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆