PostgreSQL with Python(psycopg2)中的通知不起作用

2024-09-30 20:37:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望在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代码无法工作,我做错了什么? 顺便说一句:数据库和表是用实体框架(C#)创建的


Tags: ortextimportidnewexecutecreatenotify
1条回答
网友
1楼 · 发布于 2024-09-30 20:37:32

根据NOTIFY syntax频道是一个标识符。这意味着new_Id

LISTEN new_Id

自动转换为new_id。不幸的是,pg_notify('new_Id'::text, new."Id"::text)在通道new_Id上进行通知。你有两个选择。更改触发器中的通道:

perform pg_notify('new_id'::text, new."Id"::text); 

或者将通道用双引号括在LISTEN中:

LISTEN "new_Id"

在Postgres中使用大写字母可能会引起意外

相关问题 更多 >