我希望在PostgreSQL 12的特定表 "FileInfos"
中有新条目时收到通知,因此我编写了以下触发器:
create trigger trigger1
after insert or update on public."FileInfos"
for each row execute procedure notify_id_trigger();
还有以下函数:
create or replace function notify_id_trigger()
returns trigger as $$
begin
perform pg_notify('new_Id'::text, NEW."Id"::text);
return new;
end;
$$ language plpgsql;
为了接收通知,我使用Python库psycopg2:
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
import select
def dblistener():
connection = psycopg2.connect(
host="127.0.0.1",
database="DBNAME",
user="postgres",
password="....")
connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = connection.cursor()
cur.execute("LISTEN new_Id;")
while True:
select.select([connection], [], [])
connection.poll()
while connection.notifies:
notify = connection.notifies.pop()
print("Got NOTIFY:", notify.pid, notify.channel, notify.payload)
if __name__ == '__main__':
dblistener()
很不幸,我的Python代码无法运行,我做错了什么? 另外:数据库和表是用Entity Framework(C#)创建的。