c - PostgreSQL通知处理

标签 c postgresql pointers libpq

我正在开发一个 C 应用程序,该应用程序应该与 PostgreSQL 对话。现在我需要处理服务器发送的通知和警告,但我不知道如何使其工作。

(非常不清楚)documentation说我们应该使用 PQsetNoticeReceiver 设置一个方法作为通知接收者,因为默认接收者只是将通知转发到 PQnoticeProcessor 并将其打印到 stderr。

我这样定义了一个方法

static void noticeReceiver(void *arg, const PGresult *res)

我将其设置为启动时的默认通知接收器

PQsetNoticeReceiver(conn, noticeReceiver, NULL);

在我的方法实现中,我只是将一些随机字符打印到屏幕上,但它不会被调用。逐步调试表明它被设置为默认通知接收器但从未被调用。

有什么想法吗?

最佳答案

我看到它不起作用的唯一方法是如果您在设置接收器后更改连接。请记住,接收器是连接的一个参数,因此如果您断开连接并重新连接,它就会消失。

这有效:

#include "libpq-fe.h"

static void myrecv(void *arg, const PGresult *res);

int main() {
    PGconn  *conn;
    PGresult *res;

    conn = PQconnectdb("");
    if (PQstatus(conn) == CONNECTION_BAD)
    {
        printf("connection error: %s\n",
                PQerrorMessage(conn));
        return -1;
    }

    PQsetNoticeReceiver(conn, myrecv, NULL);

    res = PQexec(conn, "select noisy_func();");
    if (PQresultStatus(res) == PGRES_FATAL_ERROR)
        printf("%s: error: %s\n",
                PQresStatus(PQresultStatus(res)),
                PQresultErrorMessage(res));

    return 0;
}

static void
myrecv(void *arg, const PGresult *res)
{
    printf("hey, got a notice saying \"%s\"\n",
            PQresultErrorField(res,
                PG_DIAG_MESSAGE_PRIMARY));
}

关于c - PostgreSQL通知处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2001189/

相关文章:

C++类复制(指针复制)

c - C语言编程中的阿姆斯特朗数

c - SDL2 程序在一段时间后停止响应

c++ - 使用复合赋值的结果作为左值

c++ - 有什么东西我可以用 C 做,但不能用 C++ 做吗?

postgresql - 如何确定是否在数据库上启用了postgis?

sql - 如何让 postgres 忽略带有重复键的插入但继续

SQL - 从多个表中获取关联数据

C++ Getter 方法打印奇怪的数字

c - 我不明白为什么我们将 "&"放在 ageAmis 的 scanf 中,而 ageAmis 是一个指针?