32.23. 示例程序 #
这些示例和其他示例可在源代码发行包的 src/test/examples 目录中找到。
例 32.1. libpq 示例程序 1
/*
* src/test/examples/testlibpq.c
*
*
* 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=postgres,并对所有其他连接参数使用环境变量或默认值。
*/
if (argc > 1)
conninfo = argv[1];
else
conninfo = "dbname = postgres";
/* 连接数据库 */
conn = PQconnectdb(conninfo);
/* 检查是否已成功建立到后端的连接 */
if (PQstatus(conn) != CONNECTION_OK)
{
fprintf(stderr, "%s", PQerrorMessage(conn));
exit_nicely(conn);
}
/* 设置始终安全的搜索路径,防止恶意用户取得控制权。 */
res = PQexec(conn,
"SELECT pg_catalog.set_config('search_path', '', false)");
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
PQclear(res);
exit_nicely(conn);
}
/*
* 不再需要 PGresult 时,应调用 PQclear 将其释放,以避免内存泄漏。
*/
PQclear(res);
/*
* 这里的测试用例使用游标,因此必须处于事务块内。
* 只需调用一次 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);
}
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);
/* 关闭 portal……这里不再检查错误…… */
res = PQexec(conn, "CLOSE myportal");
PQclear(res);
/* 结束事务 */
res = PQexec(conn, "END");
PQclear(res);
/* 关闭数据库连接并清理 */
PQfinish(conn);
return 0;
}
例 32.2. libpq 示例程序 2
/*
* src/test/examples/testlibpq2.c
*
*
* testlibpq2.c
* 测试异步通知接口
*
* 启动此程序,然后在另一个窗口中通过 psql 执行
* NOTIFY TBL2;
* 重复四次后,此程序便会退出。
*
* 或者,可以尝试更复杂的示例:
* 使用以下命令填充数据库
* (这些命令位于 src/test/examples/testlibpq2.sql 中):
*
* CREATE SCHEMA TESTLIBPQ2;
* SET search_path = TESTLIBPQ2;
* 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);
*
* 启动此程序,然后通过 psql 将以下命令执行四次:
*
* INSERT INTO TESTLIBPQ2.TBL1 VALUES (10);
*/
#ifdef WIN32
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.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;
PGnotify *notify;
int nnotifies;
/*
* 如果用户在命令行上提供了一个参数,就将其用作 conninfo 字符串;
* 否则默认设置 dbname=postgres,并对所有其他连接参数使用环境变量或默认值。
*/
if (argc > 1)
conninfo = argv[1];
else
conninfo = "dbname = postgres";
/* 连接数据库 */
conn = PQconnectdb(conninfo);
/* 检查是否已成功建立到后端的连接 */
if (PQstatus(conn) != CONNECTION_OK)
{
fprintf(stderr, "%s", PQerrorMessage(conn));
exit_nicely(conn);
}
/* 设置始终安全的搜索路径,防止恶意用户取得控制权。 */
res = PQexec(conn,
"SELECT pg_catalog.set_config('search_path', '', false)");
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
PQclear(res);
exit_nicely(conn);
}
/*
* 不再需要 PGresult 时,应调用 PQclear 将其释放,以避免内存泄漏。
*/
PQclear(res);
/*
* 发出 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);
}
PQclear(res);
/* 收到四次通知后退出。 */
nnotifies = 0;
while (nnotifies < 4)
{
/*
* 休眠,直到连接上有事件发生。这里使用 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++;
PQconsumeInput(conn);
}
}
fprintf(stderr, "Done.\n");
/* 关闭数据库连接并清理 */
PQfinish(conn);
return 0;
}
例 32.3. libpq 示例程序 3
/*
* src/test/examples/testlibpq3.c
*
*
* testlibpq3.c
* 测试在 SQL 命令文本之外独立传递的参数和二进制 I/O。
*
* 运行前,使用以下命令填充数据库
* (这些命令位于 src/test/examples/testlibpq3.sql 中):
*
* CREATE SCHEMA testlibpq3;
* SET search_path = testlibpq3;
* SET standard_conforming_strings = ON;
* 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
*
* tuple 0: got
* i = (4 bytes) 2
* t = (8 bytes) 'ho there'
* b = (5 bytes) \004\003\002\001\000
*/
#ifdef WIN32
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdint.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);
}
/*
* 此函数打印从上面注释所定义的表中以二进制格式获取的查询结果。
* 由于 main() 会使用它两次,因此将它单独提取成一个函数。
*/
static void
show_binary_results(PGresult *res)
{
int i,
j;
int i_fnum,
t_fnum,
b_fnum;
/* 使用 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;
/* 获取字段值(这里忽略它们可能为 null 的情况!) */
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");
}
}
int
main(int argc, char **argv)
{
const char *conninfo;
PGconn *conn;
PGresult *res;
const char *paramValues[1];
int paramLengths[1];
int paramFormats[1];
uint32_t binaryIntVal;
/*
* 如果用户在命令行上提供了一个参数,就将其用作 conninfo 字符串;
* 否则默认设置 dbname=postgres,并对所有其他连接参数使用环境变量或默认值。
*/
if (argc > 1)
conninfo = argv[1];
else
conninfo = "dbname = postgres";
/* 连接数据库 */
conn = PQconnectdb(conninfo);
/* 检查是否已成功建立到后端的连接 */
if (PQstatus(conn) != CONNECTION_OK)
{
fprintf(stderr, "%s", PQerrorMessage(conn));
exit_nicely(conn);
}
/* 设置始终安全的搜索路径,防止恶意用户取得控制权。 */
res = PQexec(conn, "SET search_path = testlibpq3");
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
PQclear(res);
exit_nicely(conn);
}
PQclear(res);
/*
* 此程序旨在演示如何使用 PQexecParams() 在 SQL 命令文本之外独立传递参数,
* 以及如何以二进制方式传输数据。
*
* 第一个示例以文本形式传输参数,但以二进制格式接收结果。
* 通过在 SQL 命令文本之外独立传递参数,即使数据是文本,也可以避免
* 许多繁琐的引号和转义处理。注意,参数值中的引号无需任何特殊处理。
*/
/* 这是在 SQL 命令文本之外独立传递的参数值 */
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);
}
show_binary_results(res);
PQclear(res);
/*
* 第二个示例以二进制形式传输一个整数参数,并同样以二进制形式获取结果。
*
* 虽然我们告诉 PQexecParams 让后端推断参数类型,但实际上,
* 查询文本中的参数符号经过强制类型转换,因此其类型已经确定。
* 发送二进制参数时,这是一项良好的安全措施。
*/
/* 将整数值 "2" 转换为网络字节序 */
binaryIntVal = htonl((uint32_t) 2);
/* 为 PQexecParams 设置参数数组 */
paramValues[0] = (char *) &binaryIntVal;
paramLengths[0] = sizeof(binaryIntVal);
paramFormats[0] = 1; /* 二进制 */
res = PQexecParams(conn,
"SELECT * FROM test1 WHERE i = $1::int4",
1, /* 一个参数 */
NULL, /* 让后端推断参数类型 */
paramValues,
paramLengths,
paramFormats,
1); /* 请求二进制结果 */
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
PQclear(res);
exit_nicely(conn);
}
show_binary_results(res);
PQclear(res);
/* 关闭数据库连接并清理 */
PQfinish(conn);
return 0;
}
报告文档问题
阅读 上游文档. 通过 PostgreSQL 文档反馈表单.