學習資源
核心流程
- 連接數據庫:
PQconnectdb("host=localhost dbname=test user=postgres password=123")
- 執行 SQL:
PGresult *res = PQexec(conn, "CREATE TABLE ...")
- 檢查結果:
PQresultStatus(res) == PGRES_COMMAND_OK
- 釋放結果:
PQclear(res)
- 斷開連接:
PQfinish(conn)
編譯鏈接
gcc test.c -o test -lpq -I/usr/include/postgresql
完整示例框架
#include <libpq-fe.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
PGconn *conn = PQconnectdb("dbname=test user=postgres");
if (PQstatus(conn) != CONNECTION_OK) {
fprintf(stderr, "Connection failed: %s", PQerrorMessage(conn));
PQfinish(conn); return 1;
}
// 建表
PGresult *res = PQexec(conn, "CREATE TABLE IF NOT EXISTS t(id INT, name TEXT)");
if (PQresultStatus(res) != PGRES_COMMAND_OK) { /*錯誤處理*/ }
PQclear(res);
// 插入
res = PQexec(conn, "INSERT INTO t VALUES(1, 'hello')");
PQclear(res);
// 查詢
res = PQexec(conn, "SELECT * FROM t");
if (PQresultStatus(res) == PGRES_TUPLES_OK) {
int rows = PQntuples(res);
for (int i=0; i
注意事項
- Linux 下 OS 用戶與 PostgreSQL 角色映射需配置
pg_hba.conf。
- 所有
PGresult 必須 PQclear,否則洩漏內存。
- 參數化查詢請使用
PQexecParams 防注入。