C Client Library

  • Query execution functions
    • size_t PQescapeString (char *to, const char *from, size_t length)
      • Escape an untrusted string
    • PGresult *PQexec(PGconn *conn, const char *query)
      • query is query text
      • Returns result handle
    • ExecStatusType PQresultStatus(const PGresult *res)
      • Check status of a result handle
      • PGRES_EMPTY_QUERY, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PGRES_COPY_OUT, PGRES_COPY_IN, PGRES_BAD_RESPONSE, PGRES_NONFATAL_ERROR, PGRES_FATAL_ERROR
    • int PQntuples(const PGresult *res) - number of tuples in result
    • int PQnfields(const PGresult *res) - number of fields in result
    • char* PQgetvalue(const PGresult *res,int tup_num,int field_num) - get a field
    • char *PQresultErrorMessage(const PGresult *res) - return most recent error string
    • void PQclear(PQresult *res) - free underlying memory consumed by result set
01   #include "libpq-fe.h"
02   #include <string.h>
03
04   int main(void)
05   {
06      PGconn *conn;
07      PGresult *res;
08      int i,j;
09      conn = PQconnectdb("user=postgres dbname=a");
10      if(PQstatus(conn) == CONNECTION_BAD) {
11              fprintf(stderr,"Connection failed: %s\n",PQerrorMessage(conn));
12              exit(1);
13      }
14
15      res = PQexec(conn,"SELECT id,firstname,lastname from employees;");
16      if(PQresultStatus(res) != PGRES_TUPLES_OK) {
17              fprintf(stderr,"Query failed: %s\n",PQresultErrorMessage(res));
18              exit(1);
19      }
20
21      for(i=0;i<PQntuples(res);i++) {
22              for(j=0;j<PQnfields(res);j++) {
23                      printf("%s: %s ",PQfname(res,j),PQgetvalue(res,i,j));
24              }
25              printf("\n");
26      }
27      PQclear(res);
28      PQfinish(conn);
29      return(0);
30   }

Prev

Next

Page 38