Advertisement
symdrome

Untitled

Feb 3rd, 2024
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.14 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <libpq-fe.h>
  3. #include <stdlib.h>
  4.  
  5.  
  6. PGresult * run_query(PGconn *conn, char * query)
  7. {
  8.     PGresult *res = PQexec(conn, query);
  9.  
  10.     ExecStatusType resStatus = PQresultStatus(res);
  11.  
  12.     printf("Query Status: %s\n", PQresStatus(resStatus));
  13.  
  14.     if (resStatus != PGRES_TUPLES_OK) {
  15.         fprintf(stderr, "Error while executing query: %s\n", PQerrorMessage(conn));
  16.  
  17.         PQclear(res);
  18.         PQfinish(conn);
  19.  
  20.         exit(1);
  21.     }
  22.  
  23.     return res;
  24. }
  25.  
  26. void print_query(PGresult * res)
  27. {
  28.     int rows = PQntuples(res);
  29.     int cols = PQnfields(res);
  30.  
  31.     for (int i = 0; i < rows; ++i) {
  32.         for (int j = 0; j < cols; ++j) {
  33.             printf("%s\t", PQgetvalue(res, i, j));
  34.         }
  35.         puts("");
  36.     }
  37. }
  38.  
  39. int main(void)
  40. {
  41.     char *conninfo = "dbname=postgres user=postgres password=postgres host=localhost port=5432";
  42.     PGconn *conn = PQconnectdb(conninfo);
  43.  
  44.     if (PQstatus(conn) != CONNECTION_OK) {
  45.         fprintf(stderr, "Error while connetinning in postgresSQL.\n");
  46.         PQfinish(conn);
  47.  
  48.         exit(1);
  49.     }
  50.  
  51.     char *query = "select * from nivel";
  52.  
  53.     PGresult *res = run_query(conn, query);
  54.  
  55.     print_query(res);
  56.    
  57.     PQclear(res);
  58.     PQfinish(conn);
  59.  
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement