Marcos_Carvalho

codigo da função de banco de dados

May 27th, 2019
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.56 KB | None | 0 0
  1. /*
  2.     Command line to PostgreSQL database
  3.  */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include "libpq-fe.h"
  7.  
  8.  
  9. /* IMPORTANT change this line to setup connection */
  10. #define DBDATA "host=localhost dbname=postgres user=postgres password=postgres";
  11.  
  12.  
  13. static void
  14. exit_nicely(PGconn *conn)
  15. {
  16.     PQfinish(conn);
  17.     exit(1);
  18. }
  19.  
  20. void print_tuplas(PGresult* res) {
  21.     int nFields = PQnfields(res);
  22.     int i, j;
  23.     for (i = 0; i < nFields; i++)
  24.         printf("%-15s", PQfname(res, i));
  25.     printf("\n");
  26.  
  27.     /* next, print out the rows */
  28.     for (i = 0; i < PQntuples(res); i++)
  29.     {
  30.         for (j = 0; j < nFields; j++)
  31.             printf("%-15s", PQgetvalue(res, i, j));
  32.         printf("\n");
  33.     }
  34. }
  35.  
  36. int
  37. main(int argc, char **argv)
  38. {
  39.     const char *conninfo;
  40.     PGconn     *conn;
  41.     PGresult   *res;
  42.     int         nFields;
  43.     int         i,
  44.                 j;
  45.  
  46.     /*
  47.      * If the user supplies a parameter on the command line, use it as the
  48.      * conninfo string; otherwise default to setting dbname=postgres and using
  49.      * environment variables or defaults for all other connection parameters.
  50.      */
  51.     if (argc > 1)
  52.         conninfo = argv[1];
  53.     else
  54.         conninfo = DBDATA;
  55.        
  56.     /* Make a connection to the database */
  57.     conn = PQconnectdb(conninfo);
  58.  
  59.     /* Check to see that the backend connection was successfully made */
  60.     if (PQstatus(conn) != CONNECTION_OK)
  61.     {
  62.         fprintf(stderr, "Connection to database failed: %s",
  63.                 PQerrorMessage(conn));
  64.         exit_nicely(conn);
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment