python - 使用 Python (psycopg2) 在 PostgreSQL 中的通知不起作用

标签 python postgresql triggers psycopg2 sql-function

我想在 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#) 创建的。

最佳答案

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

LISTEN new_Id

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

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

或在 LISTEN 中用双引号将 channel 括起来:

LISTEN "new_Id"

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

关于python - 使用 Python (psycopg2) 在 PostgreSQL 中的通知不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69246880/

相关文章:

python - 使用 sudo 在 python 中运行 Linux 子进程

python - IPython 笔记本和 SQL : 'ImportError: No module named sql' when running '%load_ext sql'

string - PostgreSQL : cast string to date DD/MM/YYYY

c# - 使用 EF6 创建 ddex 的 Postgresql 失败

java - 组织.hibernate.HibernateException : More than one row with the given identifier was found

mysql - 为什么我的触发器在 MySQL 中不起作用?

python - 通过 Selenium 和 python 切换到 iframe

Python,负值不超出列表范围

java - 如何使用 Java JDBC 从数据库中获取所有触发器名称?

mysql - 根据另一个表中的列值从一个表中删除记录