| PostgreSQL 8.0.0 中文文件(轉譯自 PostgreSQL 中國 製作的簡體中文版本) | ||||
|---|---|---|---|---|
| Prev | Fast Backward | Chapter 27. libpq - C 庫 | Fast Forward | Next |
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;
}