27.16. 例子程序

Example 27-1. libpq 例子程序 1

/*
 * testlibpq.c
 *
 * 测试 PostgreSQL 前端库 libpq 的 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=template1
         * 并且对其它连接使用环境变量或者缺省值。
         * 
         */
        if (argc > 1)
                conninfo = argv[1];
        else
                conninfo = "dbname = template1";


        /* 和数据库建立链接 */
        conn = PQconnectdb(conninfo);


	/*
	* 检查一下与服务器的连接是否成功建立
	*/
	if (PQstatus(conn) != CONNECTION_OK)
	{

                fprintf(stderr, "Connection to database failed: %s",
                        PQerrorMessage(conn));
                exit_nicely(conn);

	}


        /*
         * 我们这里的测试案例涉及使用游标,这种情况下我们必须在一个事务块里面。
         * 我们可以用一个简单的 PQexec(),执行
         * "select * from pg_database",完成全部操作,不过那样的话对一个例子就太简单了。
         */
	res = PQexec(conn, "BEGIN");
        if (PQresultStatus(res) != PGRES_COMMAND_OK)
        {
                fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn));
                PQclear(res);
                exit_nicely(conn);
        }

	/*
	 * 如果不再需要 PGresult 了,我们应该 PQclear,以避免内存泄漏
	 */
	 PQclear(res);

	/*
	 * 从存储数据库信息的系统表 pg_database 中抓取数据行
	 */
        res = PQexec(conn, "DECLARE myportal CURSOR FOR select * from pg_database");
        if (PQresultStatus(res) != PGRES_COMMAND_OK)
        {
                fprintf(stderr, "DECLARE CURSOR failed: %s", PQerrorMessage(conn));
                PQclear(res);
                exit_nicely(conn);
        }
        PQclear(res);

        res = PQexec(conn, "FETCH ALL in myportal");
        if (PQresultStatus(res) != PGRES_TUPLES_OK)
        {
                fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(conn));
                PQclear(res);
                exit_nicely(conn);
        }

        /* 首先,打印属性名 */
        nFields = PQnfields(res);
        for (i = 0; i < nFields; i++)
	    printf("%-15s", PQfname(res, i));
        printf("\n\n");

        /* 然后,打印数据行 */
        for (i = 0; i < PQntuples(res); i++)
        {
                for (j = 0; j < nFields; j++)
                        printf("%-15s", PQgetvalue(res, i, j));
                printf("\n");
        }

        PQclear(res);


	/* 关闭入口,我们不用关心错误检查... */
        res = PQexec(conn, "CLOSE myportal");
        PQclear(res);

	/* 提交事务 */
        res = PQexec(conn, "END");
        PQclear(res);

	/* 关闭与数据库的连接并且清理 */
        PQfinish(conn);

	return 0;

}

Example 27-2. libpq 例子程序 2

/*
 * testlibpq2.c
 *  测试异步通知接口
 *
 * 运行此程序,然后从另外一个窗口的 psql 里运行 NOTIFY TBL2;
 *
 * 或者,如果你想好玩一点,尝试下面动作∶
 * 用下面的语句填充一个数据库∶
 *
 *   CREATE TABLE TBL1 (i int4);
 *
 *   CREATE TABLE TBL2 (i int4);
 *
 *   CREATE RULE r1 AS ON INSERT TO TBL1 DO
 *     (INSERT INTO TBL2 values (new.i); NOTIFY TBL2);
 *
 * 然后做四次∶
 *
 *   INSERT INTO TBL1 values (10);
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/time.h>
#include "libpq-fe.h"

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

int
main(int argc, char **argv)
{
        const char *conninfo;
        PGconn     *conn;
        PGresult   *res;
        PGnotify   *notify;
        int                     nnotifies;

        /*
         * 如果用户在命令行上提供了参数,
         * 那么拿它当作 conninfo 字串;否则缺省设置是 dbname=template1
         * 并且对其它连接使用环境变量或者缺省值。
         * 
         */
        if (argc > 1)
                conninfo = argv[1];
        else
                conninfo = "dbname = template1";


        /* 和数据库建立链接 */
        conn = PQconnectdb(conninfo);


	/*
	* 检查一下与服务器的连接是否成功建立
	*/
	if (PQstatus(conn) != CONNECTION_OK)
	{
                fprintf(stderr, "Connection to database failed: %s",
                        PQerrorMessage(conn));
                exit_nicely(conn);
	}
        /*
         * 发出 LISTEN 命令打开来自规则 NOTIFY 的通知
         */
        res = PQexec(conn, "LISTEN TBL2");
        if (PQresultStatus(res) != PGRES_COMMAND_OK)
        {
                fprintf(stderr, "LISTEN command failed: %s", PQerrorMessage(conn));
                PQclear(res);
                exit_nicely(conn);
        }

        /*
         * 如果不再需要 PGresult 了,我们应该 PQclear,以避免内存泄漏
         */
        PQclear(res);

        /* 收到四次通知之后退出。 */
        nnotifies = 0;
        while (nnotifies < 4)
        {
                /*
                 * 睡眠,直到某些事件发生。我们使用 select(2) 等待输入,Sleep until something happens on the connection.  We use select(2)
                 * 但是也可以用 poll() 或者类似的设施
                 */
                int                     sock;
                fd_set          input_mask;

                sock = PQsocket(conn);

                if (sock < 0)
                        break;                          /* 不应该发生 */

                FD_ZERO(&input_mask);
                FD_SET(sock, &input_mask);

                if (select(sock + 1, &input_mask, NULL, NULL, NULL) < 0)
                {
                        fprintf(stderr, "select() failed: %s\n", strerror(errno));
                        exit_nicely(conn);
                }

                /* 检查输入 */
                PQconsumeInput(conn);
                while ((notify = PQnotifies(conn)) != NULL)
                {
                        fprintf(stderr,
                                        "ASYNC NOTIFY of '%s' received from backend pid %d\n",
                                        notify->relname, notify->be_pid);
                        PQfreemem(notify);
                        nnotifies++;
                }
        }

        fprintf(stderr, "Done.\n");

        /* 关闭与数据库的连接并清理 */
        PQfinish(conn);

        return 0;

}

Example 27-3. libpq 例子程序 3

/*
 * testlibpq3.c
 *              测试线外参数和二进制I/O。
 *
 * 在运行这个例子之前,用下面的命令填充一个数据库
 * (在 src/test/examples/testlibpq3.sql 里提供):
 *
 * CREATE TABLE test1 (i int4, t text, b bytea);
 *
 * INSERT INTO test1 values (1, 'joe''s place', '\\000\\001\\002\\003\\004');
 * INSERT INTO test1 values (2, 'ho there', '\\004\\003\\002\\001\\000');
 *
 * 期望的输出是:
 *
 * tuple 0: got
 *  i = (4 bytes) 1
 *  t = (11 bytes) 'joe's place'
 *  b = (5 bytes) \000\001\002\003\004
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include "libpq-fe.h"
/* 为获取 ntohl/htonl */
#include <netinet/in.h>
#include <arpa/inet.h>


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

int
main(int argc, char **argv)
{
        const char *conninfo;
        PGconn     *conn;
        PGresult   *res;
        const char *paramValues[1];
        int                     i,
                                j;
        int                     i_fnum,
                                t_fnum,
                                b_fnum;

        /*
         * 如果用户在命令行上提供了参数,
         * 那么拿它当作 conninfo 字串;否则缺省设置是 dbname=template1
         * 并且对其它连接使用环境变量或者缺省值。
         *
         */
        if (argc > 1)
                conninfo = argv[1];
        else
                conninfo = "dbname = template1";

        /* 和数据库建立链接 */
        conn = PQconnectdb(conninfo);

        /*
        * 检查一下与服务器的连接是否成功建立
        */
        if (PQstatus(conn) != CONNECTION_OK)
        {
                fprintf(stderr, "Connection to database '%s' failed.\n", PQdb(conn));
                fprintf(stderr, "%s", PQerrorMessage(conn));
                exit_nicely(conn);
        }

        /*
         * 这个程序是用来演示使用线外参数的 PQexecParams(),
         * 以及结果集的二进制传输。通过使用线外参数,我们可以避免大量
         * 枯燥的字串的引起和逃逸。请注意我们这里不需要对参数值里的引号
         * 做任何特殊的处理
         */

        /* 这里是我们的线外数据*/
        paramValues[0] = "joe's place";

        res = PQexecParams(conn,
                                           "SELECT * FROM test1 WHERE t = $1",
                                           1,           /* 一个参数 */
                                           NULL,        /* 让后端推导参数类型 */
                                           paramValues,
                                           NULL,        /* 因为是文本,所以不需要参数长度 */
                                           NULL,        /* 缺省是参数都是文本 */
                                           1);          /* 要求获取二进制结果 */

        if (PQresultStatus(res) != PGRES_TUPLES_OK)
        {
                fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
                PQclear(res);
                exit_nicely(conn);
        }

        /* 使用 PQfnumber 以避免结果里面的字段顺序的假设 */
        i_fnum = PQfnumber(res, "i");
        t_fnum = PQfnumber(res, "t");
        b_fnum = PQfnumber(res, "b");

        for (i = 0; i < PQntuples(res); i++)
        {
                char       *iptr;
                char       *tptr;
                char       *bptr;
                int                     blen;
                int                     ival;

                /* 获取字段值(我们忽略了它们可能是空的情况!!)*/
                iptr = PQgetvalue(res, i, i_fnum);
                tptr = PQgetvalue(res, i, t_fnum);
                bptr = PQgetvalue(res, i, b_fnum);

                /*
                 * INT4 的二进制形式是以网络字节序表现的,
                 * 我们最好转换成本地字节序。
                 */
                ival = ntohl(*((uint32_t *) iptr));

                /*
		 * TEXT 的二进制形式就是文本,因为 libpq 会自动给它附加一个字节零,
		 * 所以我们直接拿来当作 C 字串就很好用了。
		 *
		 * BYTEA 的二进制形式是一块字节,它可能包括嵌入的空零,因此我们应该
		 * 注意这个字段的长度。
                 */
                blen = PQgetlength(res, i, b_fnum);

                printf("tuple %d: got\n", i);
                printf(" i = (%d bytes) %d\n",
                           PQgetlength(res, i, i_fnum), ival);
                printf(" t = (%d bytes) '%s'\n",
                           PQgetlength(res, i, t_fnum), tptr);
                printf(" b = (%d bytes) ", blen);
                for (j = 0; j < blen; j++)
                        printf("\\%03o", bptr[j]);
                printf("\n\n");
        }

        PQclear(res);

        /* 关闭与数据库的连接并清理 */
        PQfinish(conn);

        return 0;
}