User Tools

Site Tools


Differences

This shows you the differences between two versions of the page.

Link to this comparison view

c:pg [2019-02-20 15:13]
ziggi created
c:pg [2020-02-15 00:57]
Line 1: Line 1:
-=====PostgresQL C client sample===== 
  
-For test purpose or as sample. 
- 
-<code c pg.c> 
- 
-#include <​stdio.h>​ 
-#include <​stdlib.h>​ 
-#include "​libpq-fe.h"​ 
- 
-static void exitNicely(PGconn * conn) { 
-    PQfinish(conn);​ 
-    exit(1); 
-} 
- 
-int main(int argc, char **argv) { 
- 
-    const char *conninfo = "​host=pgdb-ost.lazurit.us dbname=postgres user=postgres password=password";​ 
- 
-    PGconn *conn = PQconnectdb(conninfo);​ 
- 
-    if (PQstatus(conn) != CONNECTION_OK) { 
-        fprintf(stderr,​ "# connection to database failed: %s\n", PQerrorMessage(conn));​ 
-        exitNicely(conn);​ 
-    } else { 
-        fprintf(stderr,​ "# connection to database successful\n"​);​ 
-    } 
- 
-    const char *req = "​SELECT 1 + 1 AS SUM"; 
-    PGresult *res = PQexec(conn,​ req); 
- 
-    if (PQresultStatus(res) != PGRES_TUPLES_OK) { 
-        fprintf(stderr,​ "# request %s failed: %s\n", req, PQerrorMessage(conn));​ 
-        PQclear(res);​ 
-        exitNicely(conn);​ 
-    } else { 
-        fprintf(stderr,​ "# request %s successful\n",​ req); 
-    } 
- 
-    int nCols = PQnfields(res);​ 
- 
-    for (int i = 0; i < nCols; i++) { 
-        char *name = PQfname(res,​ i); 
-        printf("#​ column %d have name %s\n", i, name); 
-    } 
- 
-    int nRows = PQntuples(res);​ 
-    for (int i = 0; i < nRows; i++) { 
-        char *sum = PQgetvalue(res,​ i, 0); 
-        printf("#​ sum = %s\n", sum); 
-    } 
- 
-    PQclear(res);​ 
-    PQfinish(conn);​ 
-    return 0; 
-} 
-</​code>​ 
- 
-===Out=== 
- 
-<​file>​ 
-$ ./pg 
-# connection to database successful 
-# request SELECT 1 + 1 AS SUM successful 
-# column 0 have name sum 
-# sum = 2 
-</​file>​