encontre el siguiente ejemplo les dejo los comandos de compilar y ejecutar
g++ -I/usr/include/postgresql/ -lpq -o test.o test.cpp
./test.o
#include
#include
#include "libpq-fe.h"
int main()
{
char state_code[3]; /* holds state code entered by user */
char query_string[256]; /* holds constructed SQL query */
PGconn *conn; /* holds database connection */
PGresult *res; /* holds query result */
int i;
conn = PQconnectdb("hostaddr=127.0.0.1 dbname=digisalud user=postgres password=1234"); /* connect to the database */
if (PQstatus(conn) == CONNECTION_BAD) /* did the database connection fail? */
{
fprintf(stderr, "Connection to database failed.\n");
fprintf(stderr, "%s", PQerrorMessage(conn));
return 1;
}
printf("Enter a state code: "); /* prompt user for a state code */
scanf("%2s", state_code);
//printf ("SELECT ambulatorio FROM ambulatorio;");
sprintf(query_string,"SELECT ambulatorio,nombre_comercial FROM ambulatorio WHERE ambulatorio = '%s'", state_code);
res = PQexec(conn, query_string); /* send the query */
if (PQresultStatus(res) != PGRES_TUPLES_OK) /* did the query fail? */
{
fprintf(stderr, "SELECT query failed.\n");
PQclear(res);
PQfinish(conn);
return 1;
}
for (i = 0; i < PQntuples(res); i++) /* loop through all rows returned */
printf("%s\n", PQgetvalue(res, i, 1)); /* print the value returned */
PQclear(res); /* free result */
PQfinish(conn); /* disconnect from the database */
return 1;
}
No hay comentarios:
Publicar un comentario