开发工具:Clion远程
pg版本:14.9
编译PostgreSQL时使用make world & make install-world即可编译安装libpq库。
staticvoidexit_nicely(PGconn*conn) { PQfinish(conn); exit(1); } intmain(intargc, char**argv) { constchar*conninfo; PGconn*conn; PGresult*res; intnFields; inti, j; if(argc>1) conninfo=argv[1]; elseconninfo="dbname=postgres user=postgres password=123456 host=localhost"; conn=PQconnectdb(conninfo); if(PQstatus(conn) !=CONNECTION_OK) { fprintf(stderr, "%s", PQerrorMessage(conn)); exit_nicely(conn); } res=PQexec(conn, "SELECT pg_catalog.set_config('search_path','',false)"); if(PQresultStatus(res) !=PGRES_TUPLES_OK) { fprintf(stderr,"SET failed: %s", PQerrorMessage(conn)); PQclear(res); exit_nicely(conn); } PQclear(res); res=PQexec(conn, "BEGIN"); if(PQresultStatus(res) !=PGRES_COMMAND_OK) { fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn)); PQclear(res); exit_nicely(conn); } PQclear(res); res=PQexec(conn, "DECLARE myportal CURSOR FOR select * from pg_database"); if(PQresultStatus(res) !=PGRES_COMMAND_OK) { fprintf(stderr, "DECLARE CURSOR failed: %s", PQerrorMessage(conn)); PQclear(res); exit_nicely(conn); } PQclear(res); res=PQexec(conn, "FETCH ALL in myportal"); if(PQresultStatus(res) !=PGRES_TUPLES_OK) { fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(conn)); PQclear(res); exit_nicely(conn); } nFields=PQnfields(res); for(i=0; i<nFields; i++) printf("%-15s", PQfname(res, i)); printf("\n\n"); for(i=0; i<PQntuples(res); i++) { for(j=0; j<nFields; j++) printf("%-15s", PQgetvalue(res, i, j)); printf("\n"); } PQclear(res); res=PQexec(conn, "CLOSE myportal"); PQclear(res); res=PQexec(conn, "END"); PQclear(res); PQfinish(conn); return0; }
构建用的cmake文件
cmake_minimum_required(VERSION3.24) project(pg_testC) set(CMAKE_C_STANDARD11) set(INC_DIR/usr/local/pgsql14/include) set(LINK_DIR/usr/local/pgsql14/lib) include_directories(${INC_DIR}) link_directories(${LINK_DIR}) add_executable(pg_testtestlibpg.c) target_link_libraries(pg_testpq)