我有一个脚本可以连接到数据库并从中获取数据,我能否通过某种方式让它在数据库表中添加新记录时通知我?
我有一个脚本可以连接到数据库并从中获取数据,我能否通过某种方式让它在数据库表中添加新记录时通知我?
您可以使用 Postgresql 的 LISTEN/NOTIFY
特性。
使用 "github.com/lib/pq"
,您可以轻松地获取通知事件并对新的数据库事件做出反应。
以下是 Go 实现的示例。
使用SQL触发器和go-pg
库解决了这个问题:
Create sql function called insert_test_func
, that on INSERT
do:
PERFORM pg_notify('mychan', 'Message');
Create trigger, that executes func:
create trigger check_insert
before insert or update on *my_table_name*
for each row
execute procedure insert_test_func();
Execute this trigger
With github.com/go-pg/pg
, connect to the DB and with pg.Listen()
listening to the channel for the 'Message'
.