PostgreSQL has developed the libpq library, which can be used to write external programs in the C language to connect to the PostgreSQL database.
In the C program, you need to load the libpq Library at the beginning, # include "libpq-fe.h", pay attention to the quotation marks.
Compile this program:
Gcc-I/usr/local/pgsql/include-O PQ pqresult. C-L/usr/local/pgsql/lib-lpq
-I/usr/local/pgsql/include is the include directory after PG is installed.
-L/usr/local/pgsql/lib is the lib directory after PG is installed.
The following is a complete example:
# Include <stdio. h> # include "libpq-fe.h" // print the pgresult result voidPqresultprint(Pgresult * res) {int nfields = pqnfields (RES); int ntuples = pqntuples (RES); int I, j; for (I = 0; I <ntuples; I ++) {for (j = 0; j <nfields; j ++) {printf ("% s", pqgetvalue (Res, I, j ));} printf ("/N") ;}/// compile command: // gcc-I/usr/local/pgsql/include-O PQ pqresult. c-l/usr/local/pgsql/lib-lpqpgresult *Executequery(Char * Host, int port, char * dbname, char * query) {pgconn * conn; pgresult * res; char STR [128]; sprintf (STR, "host = % s Port = % d dbname = % s", host, port, dbname); // create a connection conn = pqconnectdb (STR); If (pqstatus (conn) = connection_bad) {fprintf (stderr, "database connection failed! HOST: % s/n ", host); fprintf (stderr," % s ", pqerrormessage (conn);} // execute sqlres = pqexec (Conn, query ); if (pqresultstatus (RES) = pgres_fatal_error) {fprintf (stderr, "% s", pqerrormessage (conn);} // command statement: Create, update, if (pqresultstatus (RES) = pgres_command_ OK) {printf ("% s/n", pqcmdtuples (RES);} // select sqlif (pqresultstatus (RES) = pgres_tuples_ OK) {} pqfinish (conn); Return res;} int main () {char * SQL = "select * from student;"; pgresult * res =Executequery("127.0.0.1", 5432, "test", SQL );Pqresultprint(RES); pqclear (RES); Return 0;} if "database connection failed" appears ",
1) to check whether the client (Program) is connected to the server (database) network, ping the command.
2) There is a file pg_mirror.conf in the directory where the server stores data. You can add the Client IP address in the last few statements to demonstrate trust in the client.