在項目中使用postgresql數據庫時要求在windows和linux雙平臺兼容。因而在windows下使用的接口在linux下爆出異常:html
psql:connections on Unix domain socket "/tmp/.s.PGSQL.5432"
通過分析和查看文檔解決了這個問題:linux
1.緣由:這是因爲在linux下鏈接pg時使用了默認的unix domain socket方式鏈接pg時出現的,而且pg的端口運行在非默認端口上(默認端口是5432)。在windows下一樣的接口使用了socket的TCP協議鏈接pg的。sql
2.在使用pgxx::connection("")時,要傳入的字符串不完整,致使了在linux下使用了unix domain socket方式鏈接。數據庫
如下是postgresql官方文檔解釋:windows
host Name of host to connect to. If a host name begins with a slash, it specifies Unix-domain communication rather than TCP/IP communication; the value is the name of the directory in which the socket file is stored. If multiple host names are specified, each will be tried in turn in the order given. The default behavior when A comma-separated list of host names is also accepted, in which case each host name in the list is tried in order. less hostaddr Numeric IP address of host to connect to. This should be in the standard IPv4 address format, e.g., Using
Note that authentication is likely to fail if A comma-separated list of Without either a host name or host address, libpq will connect using a local Unix-domain socket; or on machines without Unix-domain sockets, it will attempt to connect to |
所以,咱們的接口主要發生了2件錯誤:
1.std::string strConnection在windows下使用strConnection = "dbname="+pg_dbname+" user="+pg_username+" password="時,string的拼接出現問題。因此再拼接string字符串時使用
std::string strConnection = "dbname="; strConnection += pg_dbname.c_str(); strConnection += " user="; strConnection += pg_username.c_str(); strConnection += " password="; strConnection += pg_password.c_str(); strConnection += " hostaddr="; strConnection += pg_ip.c_str(); strConnection += " port="; strConnection += pg_port.c_str();
2.在strConnection字符串中最好加上host=localhost的配置,這樣能夠確保沒有問題。