在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 }

猜你喜欢

转载自www.cnblogs.com/sinx/p/9901434.html