Advertisement
salahzar

Untitled

May 17th, 2017
458
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.97 KB | None | 0 0
  1. /*
  2.  * testlibpq.c
  3.  *
  4.  *      Test the C version of libpq, the PostgreSQL frontend library.
  5.  */
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <libpq-fe.h>
  9.  
  10. int execCommand(PGconn * conn, char *command) ;
  11.  
  12. static void
  13. exit_nicely(PGconn *conn)
  14. {
  15.     PQfinish(conn);
  16.     exit(1);
  17. }
  18.  
  19. int
  20. main(int argc, char **argv)
  21. {
  22.     const char *conninfo;
  23.     PGconn     *conn;
  24.     PGresult   *res;
  25.     int         nFields;
  26.     int         i,
  27.                 j;
  28.  
  29.     /*
  30.      * If the user supplies a parameter on the command line, use it as the
  31.      * conninfo string; otherwise default to setting dbname=postgres and using
  32.      * environment variables or defaults for all other connection parameters.
  33.      */
  34.     if (argc > 1)
  35.         conninfo = argv[1];
  36.     else
  37.         conninfo = "dbname = postgres";
  38.  
  39.     /* Make a connection to the database */
  40.     conn = PQconnectdb(conninfo);
  41.  
  42.     /* Check to see that the backend connection was successfully made */
  43.     if (PQstatus(conn) != CONNECTION_OK)
  44.     {
  45.         fprintf(stderr, "Connection to database failed: %s",
  46.                 PQerrorMessage(conn));
  47.         exit_nicely(conn);
  48.     }
  49.  
  50.     res = PQexec(conn, "SELECT * FROM PIPPO");    
  51.    
  52.     if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  53.  
  54.         printf("No data retrieved\n");        
  55.         PQclear(res);
  56.         exit_nicely(0);
  57.     }    
  58.    
  59.     int rows = PQntuples(res);
  60.    
  61.     for(int i=0; i<rows; i++) {
  62.  
  63.         char *value = PQgetvalue(res, i, 0);
  64.         printf("%s\n", value);
  65.     }    
  66.  
  67.     PQclear(res);
  68.  
  69.  
  70.     if(execCommand(conn, "INSERT INTO PIPPO VALUES('ciao')")!=0) {
  71.         printf("Command not executed\n");        
  72.         exit_nicely(0);
  73.     }    
  74.  
  75.     PQfinish(conn);
  76.    
  77.    
  78.     return 0;
  79. }
  80.  
  81. int execCommand(PGconn * conn, char *command) {
  82.     PGresult   *res;
  83.     res = PQexec(conn, command);
  84.     if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  85.         PQclear(res);
  86.         return -1;
  87.     }
  88.     return 0;
  89.  
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement