Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <postgresql/libpq-fe.h>
- struct values
- {
- int id;
- char *field;
- struct values *next;
- };
- struct values* get_all_prise(PGresult *res , struct values *list)
- {
- struct values *list_tmp;
- list_tmp = list;
- int i;
- int sum = 0;
- for (i = 0; i < PQntuples(res); i++)
- {
- sum = PQgetlength(res,i,1);
- list->id=atoi(PQgetvalue(res, i, 0));
- list->field = malloc(sum*sizeof(char));
- memcpy(list->field,PQgetvalue(res, i, 1), sum);
- list->field[sum] = '\0';
- list->next = malloc(sizeof(struct values));
- list = list->next;
- }
- free(list);
- list = NULL;
- return list_tmp;
- }
- void show_values(PGresult *res)
- {
- int nFields = 0,i,j;
- nFields = PQnfields(res);
- for (i = 0; i < PQntuples(res); i++)
- {
- for (j = 0; j < nFields; j++)
- printf("%-15s", PQgetvalue(res, i, j));
- printf("\n");
- }
- }
- static void exit_nicely(PGconn *conn)
- {
- PQfinish(conn);
- exit(1);
- }
- int main(int argc, char **argv)
- {
- const char *conninfo;
- PGconn *conn;
- PGresult *res;
- struct values *list = malloc(sizeof(struct values));
- int nFields;
- int i,j;
- conninfo = "host=localhost port=5432 dbname=srv user=postgres password=--117";
- conn = PQconnectdb(conninfo);
- if (PQstatus(conn) != CONNECTION_OK)
- {
- fprintf(stderr, "Connection to database failed: %s",
- PQerrorMessage(conn));
- exit_nicely(conn);
- }
- res = PQexec(conn, "select * from prise");
- if (PQresultStatus(res) != PGRES_TUPLES_OK)
- {
- fprintf(stderr, "Select failed: %s", PQerrorMessage(conn));
- PQclear(res);
- exit_nicely(conn);
- }
- list = get_all_prise(res,list);
- while(list != NULL)
- {
- printf("[%d] %s\n",list->id,list->field);
- list = list->next;
- }
- PQfinish(conn);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement