When using PostgreSQL database in the project, it is required to be compatible on both windows and Linux platforms. So the interface used in windows broke out an exception in Linux
psql:connections on Unix domain socket "/tmp/.s.PGSQL.5432"
After analyzing and checking the documentation the problem was solved as follows.
1. Reason: This is due to the fact that when connecting to pg under linux, the default unix domain socket method is used to connect to pg, and the port of pg is running on a non-default port (default port is 5432). Under windows the same interface uses the TCP protocol of socket to connect to pg.
2. When using pgxx::connection(“”), the string to be passed in is incomplete, resulting in a connection using the unix domain socket method under linux.
The following is the official postgresql documentation explaining.
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.
Numeric IP address of host to connect to. This should be in the standard IPv4 address format, e.g., Using If If If both Note that authentication is likely to fail if A comma-separated list of Without either a host name or host address,libpqwill connect using a local Unix-domain socket; or on machines without Unix-domain sockets, it will attempt to connect to |
Therefore, there are 2 main things wrong with our interface.
1. std::string strConnection has a problem with string splicing when using strConnection = “dbname=”+pg_dbname+” user=”+pg_username+” password=” under windows. So when splicing the string again use
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. It is better to add the configuration of host = localhost in the strconnection string to ensure that there is no problem