- 论坛徽章:
- 7
|
参考联机帮助的 libpq 接口,这是pg自己的通信接口
贴一个8.2的例子:- /*
- * testlibpq.c
- *
- * Test C 版本的 libpq,PostgreSQL 前端库
- */
- #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";
- /* Make a connection to the database */
- conn = PQconnectdb(conninfo);
- /* 检查后端连接成功建立 */
- if (PQstatus(conn) != CONNECTION_OK)
- {
- fprintf(stderr, "Connection to database failed: %s",
- PQerrorMessage(conn));
- exit_nicely(conn);
- }
- /*
- * 我们的测试实例涉及游标的使用,这个时候我们必须使用事务块
- * 我们可以把全部事情放在一个 "select * from pg_database"
- * PQexec() 里,不过那样太简单了,不是个好例子。
- */
- /* 开始一个事务块 */
- res = PQexec(conn, "BEGIN");
- if (PQresultStatus(res) != PGRES_COMMAND_OK)
- {
- fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn));
- PQclear(res);
- exit_nicely(conn);
- }
- /*
- * 应该在结果不需要的时候 PQclear PGresult,以避免内存泄漏
- */
- 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;
- }
复制代码 |
|