gpt4 book ai didi

c - PostgreSQL通知处理

转载 作者:行者123 更新时间:2023-11-30 14:31:06 24 4
gpt4 key购买 nike

我正在开发一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com