1. 程式人生 > >在Windows中使用libpq連線postgresql資料庫

在Windows中使用libpq連線postgresql資料庫

1.首先,編譯libpq

下載原始碼,進入src目錄,interface/libpq/win32.mak 檔案中,mt命令那些行刪掉。

執行 nmake /f win32.mak

在interface/libpq/Release中可以看到libpq.lib

2.服務端配置

修改postgresql.conf

listen_addresses = '*'  # 允許所有連線
logging_collector = on # 開啟日誌   修改pg_hba.conf,新增信任。   3.編寫程式碼  
 1
// ptest.cpp : 此檔案包含 "main" 函式。程式執行將在此處開始並結束。 2 // 3 4 #include "pch.h" 5 #include <iostream> 6 #include <libpq-fe.h> 7 8 #pragma comment(lib, "libpq.lib") 9 #pragma comment(lib, "ws2_32.lib") 10 #pragma comment(lib, "Secur32.lib") 11 12 int main() 13 { 14 const char *conninfo = "
postgresql://[email protected]:5432/testdb"; 15 16 PGconn *conn; 17 PGresult *res; 18 19 conn = PQconnectdb(conninfo); 20 21 if (PQstatus(conn) != CONNECTION_OK) 22 { 23 std::cerr << "Connection to db failed:" << PQerrorMessage(conn); 24 PQfinish(conn);
25 exit(1); 26 } 27 28 std::cout << "Connect successful!" << std::endl; 29 30 res = PQexec(conn, "SELECT * FROM pg_tables;"); 31 32 if (PQresultStatus(res) != PGRES_TUPLES_OK) 33 { 34 std::cerr << "EXECUTION failed:" << PQerrorMessage(conn); 35 PQclear(res); 36 PQfinish(conn); 37 exit(1); 38 } 39 40 int nFields; 41 nFields = PQnfields(res); 42 //列印屬性名字 43 for (int i = 0; i < nFields; ++i) 44 { 45 std::cout << PQfname(res, i) << std::ends; 46 } 47 std::cout << "\n---" << std::endl; 48 49 //列印行 50 for (int i = 0; i < PQntuples(res); ++i) 51 { 52 for (int j = 0; j < nFields; ++j) 53 { 54 std::cout << PQgetvalue(res, i, j) <<'\t'<< std::ends; 55 } 56 std::cout << std::endl; 57 } 58 59 60 PQclear(res); 61 62 PQfinish(conn); 63 64 getchar(); 65 66 return 0; 67 }