Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2018
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.67 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <libpq-fe.h>
  3.  
  4. // program dla danego zapytania SQL printuje je w postaci JSON na ekran
  5. // przyklad uzycia:
  6. // ./zadanie "select * from kurs1.kurs;"
  7.  
  8. // funkcja drukujaca na ekran rezultat polecania w formie JSON
  9. void printJSON(PGresult *result) {
  10.  
  11.     int row, field;
  12.     int nrows   = PQntuples(result);
  13.     int nfields = PQnfields(result);
  14.     printf("[");
  15.     for(row = 0; row < nrows; ++row) {
  16.             printf("{");       
  17.         for(field = 0; field < nfields; field++) {
  18.                 printf("\"%s\":\"%s\"", PQfname(result, field), PQgetvalue(result, row, field), PQgetlength(result, row, field));
  19.         if (field != nfields -1)
  20.             printf(", ");  
  21.     }
  22.         printf(row != nrows - 1 ? "},\n" : "}");
  23.     }
  24.     printf("]\n");
  25.  
  26.     return;
  27. }
  28.  
  29.  
  30.  
  31. void doSQL(PGconn *conn, char *command){
  32.     PGresult *result;
  33.     printf("------------------------------\n");
  34.     printf("%s\n", command);
  35.     result = PQexec(conn, command);
  36.     printf("status is : %s\n", PQresStatus(PQresultStatus(result)));
  37.     printf("#rows affected: %s\n", PQcmdTuples(result));
  38.     printf("JSON: %s\n", PQresultErrorMessage(result));
  39.     if (PQresultStatus(result) == PGRES_TUPLES_OK)
  40.         printJSON(result);
  41.     PQclear(result);
  42. }
  43.  
  44. int main(int argc, char * argv[] ){
  45.     PGresult *result;
  46.     PGconn *conn;
  47.     const char *connection_str = "host=localhost port=5432 dbname=u6podsiadlo user=u6podsiadlo  password=6podsiadlo";
  48.     conn = PQconnectdb(connection_str);
  49.     if (PQstatus(conn) == CONNECTION_BAD) {
  50.             fprintf(stderr, "Connection to %s failed, %s", connection_str, PQerrorMessage(conn));
  51.     }
  52.     else {
  53.             printf("Connected OK\n");
  54.             doSQL(conn, argv[1]);
  55.     }    
  56.     PQfinish(conn);
  57.     return EXIT_SUCCESS;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement