Libpq:接收过程输出参数的值

问题描述 投票:0回答:1

我正在使用

libpq
构建一个应用程序,并且文档对于执行对 PostgreSQL 数据库中的过程和函数的调用不是很清楚。我已经能够通过
libpq
结果检索函数调用的返回值,但我不确定如何获取函数或过程未专门返回的输出参数的值。有没有办法做到这一点,如果有的话,怎么做?

c postgresql libpq
1个回答
0
投票

输出参数和查询结果返回方式相同。这是一个基于 libpq documentation

中的代码的简单示例

首先创建一个程序来测试:

CREATE PROCEDURE inc_int(INOUT a integer)
LANGUAGE plpgsql
AS $$
BEGIN
a := a+1;
END;
$$;

然后是一个最小的 C 程序来调用该过程:

#include <stdio.h>
#include <stdlib.h>
#include "libpq-fe.h"

static void
exit_nicely(PGconn *conn)
{
    PQfinish(conn);
    exit(1);
}

int
main(int argc, char **argv)
{
    const char *conninfo;
    PGconn     *conn;
    PGresult   *res;
    int         nFields;
    int         i,
                j;

    conninfo = "dbname = postgres";

    /* Make a connection to the database */
    conn = PQconnectdb(conninfo);

    /* Check to see that the backend connection was successfully made */
    if (PQstatus(conn) != CONNECTION_OK)
    {
        fprintf(stderr, "%s", PQerrorMessage(conn));
        exit_nicely(conn);
    }

    res = PQexec(conn, " CALL inc_int(1) ");
    if (PQresultStatus(res) != PGRES_TUPLES_OK)
    {
        fprintf(stderr, "select failed: %s", PQerrorMessage(conn));
        PQclear(res);
        exit_nicely(conn);
    }
    
   
    /* first, print out the attribute names */
    nFields = PQnfields(res);
    for (i = 0; i < nFields; i++)
        printf("%-15s", PQfname(res, i));
    printf("\n\n");

    /* next, print out the rows */
    for (i = 0; i < PQntuples(res); i++)
    {
        for (j = 0; j < nFields; j++)
            printf("%-15s", PQgetvalue(res, i, j));
        printf("\n");
    }

    PQclear(res);


    /* close the connection to the database and cleanup */
    PQfinish(conn);

    return 0;
}

运行生成的程序:

./pgtest                                                                         
a              

2              
© www.soinside.com 2019 - 2024. All rights reserved.