首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

PostgreSQL C/C++ API (libpq) 入門:連接、建表、插入與查詢示例

     編輯:關於C語言

學習資源

核心流程

  1. 連接數據庫:PQconnectdb("host=localhost dbname=test user=postgres password=123")
  2. 執行 SQL:PGresult *res = PQexec(conn, "CREATE TABLE ...")
  3. 檢查結果:PQresultStatus(res) == PGRES_COMMAND_OK
  4. 釋放結果:PQclear(res)
  5. 斷開連接: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 防注入。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved