2020-08-14修改
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libpq-fe.h>
#define SE_LIBPQPARAM_COUNT (9)
#define SE_UNI_SINGLE_CHAR_SIZE (1)
#define SE_LIBPQ_CONN_MAXCOUNT (16)
#define SE_LIBPQKEY_MAX_MEMLEN (SE_LIBPQ_CONN_MAXCOUNT * SE_UNI_SINGLE_CHAR_SIZE + sizeof(char))
#define SE_LIBPQVALUE_MAX_MEMLEN (SE_LIBPQ_CONN_MAXCOUNT * SE_UNI_SINGLE_CHAR_SIZE+ sizeof(char))
#define SE_SAFE_FREE(x)\
do {\
if(NULL != x) { \
free(x); x = NULL; \
} \
} while (0)
#define SE_SAFE_DBCLOSE(x)\
do {\
if(NULL != x) { \
PQfinish(x); x = NULL; \
} \
} while (0)
const char* getPGPingName(PGPing val) {
switch (val) {
case PQPING_OK: return "PQPING_OK";
case PQPING_REJECT: return "PQPING_REJECT";
case PQPING_NO_RESPONSE: return "PQPING_NO_RESPONSE";
case PQPING_NO_ATTEMPT: return "PQPING_NO_ATTEMPT";
default:return"UNKNOWN";
}
}
int main() {
PGconn *conn = NULL;
PGPing result = PQPING_OK;
char **keys = NULL, *tmpKeys;
char **vals = NULL, *tmpVals;
size_t arrHeadSize= (sizeof(char*) * SE_LIBPQPARAM_COUNT) + sizeof(char*);
keys = (char **)malloc(arrHeadSize+ (SE_LIBPQPARAM_COUNT * SE_LIBPQKEY_MAX_MEMLEN));
if (NULL == keys)
exit(-1);
vals = (char **)malloc(arrHeadSize+ (SE_LIBPQPARAM_COUNT * SE_LIBPQVALUE_MAX_MEMLEN));
if (NULL == vals) {
SE_SAFE_FREE(keys);
exit(-1);
}
tmpKeys = (char *)keys + arrHeadSize;
tmpVals = (char *)vals + arrHeadSize;
for (int i = 0; i < SE_LIBPQPARAM_COUNT; ++i) {
keys[i] = tmpKeys;
tmpKeys += SE_LIBPQKEY_MAX_MEMLEN;
vals[i] = tmpVals;
tmpVals += SE_LIBPQVALUE_MAX_MEMLEN;
}
keys[SE_LIBPQPARAM_COUNT-1] = NULL;
vals[SE_LIBPQPARAM_COUNT-1] = NULL;
strncpy(keys[0], "hostaddr", SE_LIBPQKEY_MAX_MEMLEN);
strncpy(keys[1], "port", SE_LIBPQKEY_MAX_MEMLEN);
strncpy(keys[2], "dbname", SE_LIBPQKEY_MAX_MEMLEN);
strncpy(keys[3], "user", SE_LIBPQKEY_MAX_MEMLEN);
strncpy(keys[4], "password", SE_LIBPQKEY_MAX_MEMLEN);
strncpy(keys[5], "connect_timeout", SE_LIBPQKEY_MAX_MEMLEN);
strncpy(keys[6], "client_encoding", SE_LIBPQKEY_MAX_MEMLEN);
strncpy(keys[7], "application_name", SE_LIBPQKEY_MAX_MEMLEN);
strncpy(vals[0], "192.168.1.252", SE_LIBPQVALUE_MAX_MEMLEN);
strncpy(vals[1], "5432", SE_LIBPQVALUE_MAX_MEMLEN);
strncpy(vals[2], "数据库名", SE_LIBPQVALUE_MAX_MEMLEN);
strncpy(vals[3], "用户名", SE_LIBPQVALUE_MAX_MEMLEN);
strncpy(vals[4], "密码", SE_LIBPQVALUE_MAX_MEMLEN);
strncpy(vals[5], "10", SE_LIBPQVALUE_MAX_MEMLEN);
strncpy(vals[6], "GBK", SE_LIBPQVALUE_MAX_MEMLEN);
strncpy(vals[7], "libpq12345678915", SE_LIBPQVALUE_MAX_MEMLEN);
for (int i = 0; i < SE_LIBPQPARAM_COUNT; ++i)
printf("%s:%s\n", keys[i], vals[i]);
result = PQpingParams(keys, vals, 1);
printf("连接状态:%s(%d)\n", getPGPingName(result), result);
conn = PQconnectdbParams(keys, vals, 1);
if (NULL == conn) {
SE_SAFE_FREE(keys);
SE_SAFE_FREE(vals);
exit(-1);
}
SE_SAFE_DBCLOSE(conn);
SE_SAFE_FREE(keys);
SE_SAFE_FREE(vals);
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4b4259eae5395fe67aa7588353f899ed.png)