我是一个尝试学习 PostgreSQL 的新手。我正在尝试通过使用 libpq 的 C 程序连接到我的 postgres 服务器。
这是服务器状态:
home/planb/postgresql-9.2.4/Project status -o "-p 5555"
pg_ctl: server is running (PID: 2338)
/usr/local/pgsql/bin/postgres "-D" "/home/planb/postgresql-9.2.4/Project" "-p5555"
当我编译时,我使用:
gcc -I /usr/local/pgsql/include -L /usr/local/pgsql/lib test.c -lpq
当我使用 ./a.out 运行程序时,它显示:
Connection error
我相信我没有正确使用 PQconnectdb,但它可能是其他事情。
这是我的 C 文件:test.c
#include <stdio.h>
#include <stdlib.h>
#include <libpq-fe.h>
int main(int argc, char* argv[])
{
//Start connection
PGconn* connection = PQconnectdb("hostaddr=168.105.127.3 port=5555 dbname=Project username=postgres password=password");
if (PQstatus(connection) ==CONNECTION_BAD)
{
printf("Connection error\n");
PQfinish(connection);
return -1; //Execution of the program will stop here
}
printf("Connection ok\n");
//End connection
PQfinish(connection);
printf("Disconnected\n");
return 0;
}
非常感谢任何输入,谢谢!
弄清楚了!
我没有使用有效的主机地址。我将其替换为:
host=localhost
我还删除了 dbname=Project。当我运行它时,我得到:
Msg: Connection ok
Disconnected