libpqxx接口的在linux下的使用,解决psql:connections on Unix domain socket "/tmp/.s.PGSQL.5432"错误
在项目中使用postgresql数据库时要求在windows和linux双平台兼容。于是在windows下使用的接口在linux下爆出异常:
psql:connections on Unix domain socket "/tmp/.s.PGSQL.5432"
经过分析和查看文档解决了这个问题:
1.原因:这是由于在linux下连接pg时使用了默认的unix domain socket方式连接pg时出现的,并且pg的端口运行在非默认端口上(默认端口是5432)。在windows下同样的接口使用了socket的TCP协议连接pg的。
2.在使用pgxx::connection("")时,要传入的字符串不完整,导致了在linux下使用了unix domain socket方式连接。
以下是postgresql官方文档解释:
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. 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的配置,这样可以确保没有问题。