Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * testlibpq.c
- *
- * Test the C version of libpq, the PostgreSQL frontend library.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <libpq-fe.h>
- int execCommand(PGconn * conn, char *command) ;
- static void
- exit_nicely(PGconn *conn)
- {
- PQfinish(conn);
- exit(1);
- }
- int
- main(int argc, char **argv)
- {
- const char *conninfo;
- PGconn *conn;
- PGresult *res;
- int nFields;
- int i,
- j;
- /*
- * If the user supplies a parameter on the command line, use it as the
- * conninfo string; otherwise default to setting dbname=postgres and using
- * environment variables or defaults for all other connection parameters.
- */
- if (argc > 1)
- conninfo = argv[1];
- else
- conninfo = "dbname = postgres";
- /* Make a connection to the database */
- conn = PQconnectdb(conninfo);
- /* Check to see that the backend connection was successfully made */
- if (PQstatus(conn) != CONNECTION_OK)
- {
- fprintf(stderr, "Connection to database failed: %s",
- PQerrorMessage(conn));
- exit_nicely(conn);
- }
- res = PQexec(conn, "SELECT * FROM PIPPO");
- if (PQresultStatus(res) != PGRES_TUPLES_OK) {
- printf("No data retrieved\n");
- PQclear(res);
- exit_nicely(0);
- }
- int rows = PQntuples(res);
- for(int i=0; i<rows; i++) {
- char *value = PQgetvalue(res, i, 0);
- printf("%s\n", value);
- }
- PQclear(res);
- if(execCommand(conn, "INSERT INTO PIPPO VALUES('ciao')")!=0) {
- printf("Command not executed\n");
- exit_nicely(0);
- }
- PQfinish(conn);
- return 0;
- }
- int execCommand(PGconn * conn, char *command) {
- PGresult *res;
- res = PQexec(conn, command);
- if (PQresultStatus(res) != PGRES_COMMAND_OK) {
- PQclear(res);
- return -1;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement