W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
這些例子和其他例子可以在源代碼發(fā)布的src/test/examples
目錄中找到。
例 33.1. libpq 例子程序 1
/*
* src/test/examples/testlibpq.c
*
*
* testlibpq.c
*
* 測試 libpq(PostgreSQL 前端庫) 的 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;
/*
* 如果用戶在命令行上提供了一個參數(shù),將它用作連接信息串。
* 否則默認(rèn)用設(shè)置 dbname=postgres 并且為所有其他鏈接參數(shù)使用環(huán)境變量或默認(rèn)值。
*/
if (argc > 1)
conninfo = argv[1];
else
conninfo = "dbname = postgres";
/* 建立到數(shù)據(jù)庫的一個連接 */
conn = PQconnectdb(conninfo);
/* 檢查看后端連接是否成功建立 */
if (PQstatus(conn) != CONNECTION_OK)
{
fprintf(stderr, "Connection to database failed: %s",
PQerrorMessage(conn));
exit_nicely(conn);
}
/* 設(shè)置總是安全的搜索路徑,這樣惡意用戶就無法取得控制。 */
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 時,應(yīng)該 PQclear 它來避免內(nèi)存泄露
*/
PQclear(res);
/*
* 我們的測試案例這里涉及使用一個游標(biāo),對它我們必須用在一個事務(wù)塊內(nèi)。
* 我們可以在一個單一的 "select * from pg_database" 的 PQexec() 中做整個事情,
* 但是作為一個好的例子它太瑣碎。
*/
/* 開始一個事務(wù)塊 */
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 取得行,它是數(shù)據(jù)庫的系統(tǒng)目錄
*/
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);
/* 關(guān)閉入口,我們不需要考慮檢查錯誤 */
res = PQexec(conn, "CLOSE myportal");
PQclear(res);
/* 結(jié)束事務(wù) */
res = PQexec(conn, "END");
PQclear(res);
/* 關(guān)閉到數(shù)據(jù)庫的連接并且清理 */
PQfinish(conn);
return 0;
}
例 33.2. libpq例子程序 2
/*
* src/test/examples/testlibpq2.c
*
*
* testlibpq2.c
* 測試異步通知接口
*
* 開始這個程序,然后在另一個窗口的 psql 中做
* NOTIFY TBL2;
* 重復(fù)四次來讓這個程序退出。
*
* 或者,如果你想要得到奇妙的事情,嘗試:
* 用下列命令填充一個數(shù)據(jù)庫
* (在 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/time.h>
#include <sys/types.h>
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#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;
/*
* 用過用戶在命令行上提供了一個參數(shù),將它用作連接信息串。
* 否則默認(rèn)用設(shè)置 dbname=postgres 并且為所有其他鏈接參數(shù)使用環(huán)境變量或默認(rèn)值。
*/
if (argc > 1)
conninfo = argv[1];
else
conninfo = "dbname = postgres";
/* 建立一個到數(shù)據(jù)庫的連接 */
conn = PQconnectdb(conninfo);
/* 檢查后端連接是否成功建立 */
if (PQstatus(conn) != CONNECTION_OK)
{
fprintf(stderr, "Connection to database failed: %s",
PQerrorMessage(conn));
exit_nicely(conn);
}
/* 設(shè)置總是安全的搜索路徑,這樣惡意用戶就無法取得控制。 */
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 時,應(yīng)該 PQclear 它來避免內(nèi)存泄露
*/
PQclear(res);
/*
* 發(fā)出 LISTEN 命令啟用來自規(guī)則的 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)
{
/*
* 休眠到在連接上發(fā)生某些事情。我們使用 select(2) 來等待輸入,但是你也可以使用 poll() 或相似的設(shè)施。
*/
int sock;
fd_set input_mask;
sock = PQsocket(conn);
if (sock < 0)
break; /* 不應(yīng)該發(fā)生 */
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);
}
/* 現(xiàn)在檢查輸入 */
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");
/* 關(guān)閉到數(shù)據(jù)庫的連接并且清理 */
PQfinish(conn);
return 0;
}
例 33.3. libpq例子程序 3
/*
* src/test/examples/testlibpq3.c
*
*
* testlibpq3.c
* 測試線外參數(shù)和二進(jìn)制 I/O。
*
* 在運行之前,使用下列命令填充一個數(shù)據(jù)庫(在 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"
/* for ntohl/htonl */
#include <netinet/in.h>
#include <arpa/inet.h>
static void
exit_nicely(PGconn *conn)
{
PQfinish(conn);
exit(1);
}
/*
* 這個函數(shù)打印一個查詢結(jié)果,該結(jié)果以二進(jìn)制格式從上面的注釋中定義的表中取得。
* 我們把它分離出來是因為 main() 函數(shù)需要使用它兩次。
*/
static void
show_binary_results(PGresult *res)
{
int i,
j;
int i_fnum,
t_fnum,
b_fnum;
/* 使用 PQfnumber 來避免假定結(jié)果中域的順序 */
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;
/* 得到域值(我們忽略它們?yōu)榭罩档目赡苄裕。?*/
iptr = PQgetvalue(res, i, i_fnum);
tptr = PQgetvalue(res, i, t_fnum);
bptr = PQgetvalue(res, i, b_fnum);
/*
* INT4 的二進(jìn)制表示是按照網(wǎng)絡(luò)字節(jié)序的,我們最好強(qiáng)制為本地字節(jié)序。
*/
ival = ntohl(*((uint32_t *) iptr));
/*
* TEXT 的二進(jìn)制表示是文本,并且因為 libpq 會為它追加一個零字節(jié),它將工作得和 C 字符串一樣好。
*
* BYTEA 的二進(jìn)制表示是一堆字節(jié),其中可能包含嵌入的空值,因此我們必須注意域長度。
*/
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;
/*
* 如果用戶在命令行上提供了一個參數(shù),將它用作連接信息串。
* 否則默認(rèn)用設(shè)置 dbname=postgres 并且為所有其他鏈接參數(shù)使用環(huán)境變量或默認(rèn)值。
*/
if (argc > 1)
conninfo = argv[1];
else
conninfo = "dbname = postgres";
/* 建立一個到數(shù)據(jù)庫的連接 */
conn = PQconnectdb(conninfo);
/* 檢查看后端連接是否成功被建立 */
if (PQstatus(conn) != CONNECTION_OK)
{
fprintf(stderr, "Connection to database failed: %s",
PQerrorMessage(conn));
exit_nicely(conn);
}
/* 設(shè)置總是安全的搜索路徑,這樣惡意用戶就無法取得控制。 */
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);
/*
* 這個程序的要點在于用線外參數(shù)展示 PQexecParams() 的使用,以及數(shù)據(jù)的二進(jìn)制傳輸。
*
* 第一個例子將參數(shù)作為文本傳輸,但是以二進(jìn)制格式接收結(jié)果。
* 通過使用線外參數(shù),我們能夠避免使用繁雜的引用和轉(zhuǎn)義,即便數(shù)據(jù)是文本。
* 注意我們怎么才能對參數(shù)值中的引號不做任何事情。
*/
/* 這里是我們的線外參數(shù)值 */
paramValues[0] = "joe's place";
res = PQexecParams(conn,
"SELECT * FROM test1 WHERE t = $1",
1, /* 一個參數(shù) */
NULL, /* 讓后端推導(dǎo)參數(shù)類型 */
paramValues,
NULL, /* 因為文本不需要參數(shù)長度 */
NULL, /* 對所有文本參數(shù)的默認(rèn)值 */
1); /* 要求二進(jìn)制結(jié)果 */
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
PQclear(res);
exit_nicely(conn);
}
show_binary_results(res);
PQclear(res);
/*
* 在第二個例子中,我們以二進(jìn)制形式傳輸一個整數(shù)參數(shù),并且再次以二進(jìn)制形式接收結(jié)果。
*
* 盡管我們告訴 PQexecParams 我們讓后端推導(dǎo)參數(shù)類型,我們實際上通過在查詢文本中造型參數(shù)符號來強(qiáng)制該決定。
* 在發(fā)送二進(jìn)制參數(shù)時,這是一種好的安全測度。
*/
/* 將整數(shù)值 "2" 轉(zhuǎn)換為網(wǎng)絡(luò)字節(jié)序 */
binaryIntVal = htonl((uint32_t) 2);
/* 為 PQexecParams 設(shè)置參數(shù)數(shù)組 */
paramValues[0] = (char *) &binaryIntVal;
paramLengths[0] = sizeof(binaryIntVal);
paramFormats[0] = 1; /* binary */
res = PQexecParams(conn,
"SELECT * FROM test1 WHERE i = $1::int4",
1, /* 一個參數(shù) */
NULL, /* 讓后端推導(dǎo)參數(shù)類型 */
paramValues,
paramLengths,
paramFormats,
1); /* 要求二進(jìn)制結(jié)果 */
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
PQclear(res);
exit_nicely(conn);
}
show_binary_results(res);
PQclear(res);
/* 關(guān)閉到數(shù)據(jù)庫的連接并清理 */
PQfinish(conn);
return 0;
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: