Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.08 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <postgresql/libpq-fe.h>
  5.  
  6. struct values
  7. {
  8.   int id;
  9.   char *field;
  10.   struct values *next;
  11. };
  12.  
  13.  
  14. struct values* get_all_prise(PGresult *res , struct values *list)
  15. {
  16.  struct values *list_tmp;
  17.  list_tmp = list;
  18.  int i;
  19.  int sum = 0;
  20.     for (i = 0; i < PQntuples(res); i++)
  21.     {
  22.             sum = PQgetlength(res,i,1);
  23.             list->id=atoi(PQgetvalue(res, i, 0));
  24.             list->field = malloc(sum*sizeof(char));
  25.             memcpy(list->field,PQgetvalue(res, i, 1), sum);
  26.             list->field[sum] = '\0';
  27.             list->next = malloc(sizeof(struct values));
  28.             list = list->next;
  29.     }
  30.            free(list);
  31.            list = NULL;
  32.      return list_tmp;
  33. }
  34. void show_values(PGresult *res)
  35. {
  36.  int nFields = 0,i,j;
  37.  nFields = PQnfields(res);
  38.  
  39.     for (i = 0; i < PQntuples(res); i++)
  40.     {
  41.         for (j = 0; j < nFields; j++)
  42.             printf("%-15s", PQgetvalue(res, i, j));
  43.         printf("\n");
  44.     }
  45. }
  46.  
  47. static void exit_nicely(PGconn *conn)
  48. {
  49.     PQfinish(conn);
  50.     exit(1);
  51. }
  52.  
  53. int main(int argc, char **argv)
  54. {
  55.     const char *conninfo;
  56.     PGconn     *conn;
  57.     PGresult   *res;
  58.     struct values *list = malloc(sizeof(struct values));
  59.     int         nFields;
  60.     int         i,j;
  61.    
  62.     conninfo = "host=localhost port=5432 dbname=srv user=postgres password=--117";
  63.  
  64.     conn = PQconnectdb(conninfo);
  65.  
  66.     if (PQstatus(conn) != CONNECTION_OK)
  67.     {
  68.         fprintf(stderr, "Connection to database failed: %s",
  69.                 PQerrorMessage(conn));
  70.         exit_nicely(conn);
  71.     }
  72.  
  73.     res = PQexec(conn, "select * from prise");
  74.     if (PQresultStatus(res) != PGRES_TUPLES_OK)
  75.     {
  76.         fprintf(stderr, "Select failed: %s", PQerrorMessage(conn));
  77.         PQclear(res);
  78.         exit_nicely(conn);
  79.     }
  80.  
  81.     list = get_all_prise(res,list);
  82.       while(list != NULL)
  83.             {
  84.                  printf("[%d] %s\n",list->id,list->field);
  85.                  list = list->next;
  86.             }
  87.     PQfinish(conn);
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement