|
C Client Library
- Non-blocking database connection functions
- Reasonably high connection startup overhead
- TCP overhead (if applicable)
- PGconn *PQconnectStart(const char *conninfo)
- conninfo as for PQconnectdb()
- PostgresPollingStatusType PQconnectPoll(PGconn *conn)
- Check status of connection
- PGRES_POLLING_READING - waiting for read on socket
- PGRES_POLLING_WRITING - waiting write on socket
- PGRES_POLLING_ACTIVE - network connection established, wait for PGRES_POLLING_OK
- PGRES_POLLING_OK - connection successfully established
- PGRES_POLLING_FAILED - connection failed
01 #include "libpq-fe.h"
02 #include <stdio.h>
03
04 #include <sys/time.h>
05 #include <sys/types.h>
06 #include <unistd.h>
07 #include <errno.h>
08 #include <string.h>
09
10 int main(void)
11 {
12 int i;
13 PGconn *conn;
14 struct timeval tv;
15 fd_set in, out, exp;
16
17 conn = PQconnectStart("user=swm dbname=template1");
18
19 if(PQstatus(conn) == CONNECTION_BAD)
20 exit(1);
21
22 tv.tv_sec = 1;
23 tv.tv_usec = 0;
24
25 i = 0;
26 while(i<100) {
27 switch(PQconnectPoll(conn)) {
28 case PGRES_POLLING_ACTIVE:
29 fprintf(stderr,"polling active\n");
30 break;
31 case PGRES_POLLING_WRITING:
32 fprintf(stderr,"polling writing\n");
33 FD_ZERO(&in);
34 FD_ZERO(&out);
35 FD_ZERO(&exp);
36 FD_SET(PQsocket(conn),&out);
37 FD_SET(PQsocket(conn),&exp);
38 select(PQsocket(conn) + 1,&in,&out,&exp,&tv);
39 break;
40 case PGRES_POLLING_READING:
41 fprintf(stderr,"polling reading\n");
42 FD_ZERO(&in);
43 FD_ZERO(&out);
44 FD_ZERO(&exp);
45 FD_SET(PQsocket(conn),&in);
46 FD_SET(PQsocket(conn),&exp);
47 select(PQsocket(conn) + 1,&in,&out,&exp,&tv);
48 break;
49 case PGRES_POLLING_OK:
50 fprintf(stderr,"connection ready\n");
51 break;
52 case PGRES_POLLING_FAILED:
53 fprintf(stderr,"failed\n"); exit(1);
54 }
55 i++;
56 }
57 PQfinish(conn);
58 }
59
Page 37
|