代码如下:
[root@lex tst]# cat testlibpq.c /* * testlibpq.c * Test the C version of LIBPQ, the POSTGRES frontend library. */ #include <stdio.h> #include <stdlib.h> #include "libpq-fe.h" static void exit_nicely(PGconn *conn) { PQfinish(conn); exit(EXIT_SUCCESS); } int main() { int nFields; int i, j; #ifdef DEBUG FILE *debug; #endif /* DEBUG */ PGconn *conn; PGresult *res; const char *conninfo="postgresql://postgres:postgres@localhost:5432/postgres"; /* make a connection to the database */ conn = PQconnectdb(conninfo); /* check to see that the backend connection was successfully made */ if (PQstatus(conn) == CONNECTION_BAD) { fprintf(stderr, "Connection to database failed. "); fprintf(stderr, "%s", PQerrorMessage(conn)); exit_nicely(conn); } #ifdef DEBUG debug = fopen("/tmp/trace.out", "w"); PQtrace(conn, debug); #endif /* DEBUG */ /* start a transaction block */ res = PQexec(conn, "BEGIN"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "BEGIN command failed "); PQclear(res); exit_nicely(conn); } PQclear(res); //////////////////////////////////////////////////////////////////////////////////// const char *stmt_name = "test_stmt"; const char *stmt = "select * from customers where cust_id=$1"; Oid param_types[1]; param_types[0] = 0; ///let db to judge it. res = PQprepare(conn, stmt_name, stmt,1,param_types); if (PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "PQprepare failed "); PQclear(res); exit_nicely(conn); } PQclear(res); const char* custid = "3"; const char* param_values[1]; param_values[0] =custid; int param_lengths[1]; param_lengths[0] = 1; int param_formats[1]; param_formats[0] = 0; res = PQexecPrepared(conn, stmt_name, 1, param_values, param_lengths, param_formats, 0); if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "PQexecPrepared statement didn't return tuples properly "); PQclear(res); exit_nicely(conn); } /////////////////////////////////////////////////////////////////////////////////// /* first, print out the attribute names */ nFields = PQnfields(res); for (i = 0; i < nFields; i++) printf("%-15s", PQfname(res, i)); printf(" "); /* next, print out the instances */ for (i = 0; i < PQntuples(res); i++) { for (j = 0; j < nFields; j++) printf("%-15s", PQgetvalue(res, i, j)); printf(" "); } PQclear(res); /* end the transaction */ res = PQexec(conn, "END"); PQclear(res); /* close the connection to the database and cleanup */ PQfinish(conn); #ifdef DEBUG fclose(debug); #endif /* DEBUG */ return 0; } [root@lex tst]#
编译和运行:
[root@lex tst]# gcc -c -I/usr/local/pgsql/include testlibpq.c [root@lex tst]# gcc -o testlibpq testlibpq.o -L/usr/local/pgsql/lib -lpq [root@lex tst]# ./testlibpq cust_id cust_name 3 Taylor [root@lex tst]#