【问题标题】:Cannot connect to postgreSQL server using libpq无法使用 libpq 连接到 postgreSQL 服务器
【发布时间】:2013-10-01 04:31:09
【问题描述】:

我是一个尝试学习 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

【问题讨论】:

  • 您可以使用带有这些参数的psql 进行连接吗? PQerrorMessage(connection) 有什么要说的?
  • 感谢您的快速回复!我可以用psql连接没有问题。错误消息显示:无法将主机名“tcp://0.0.0.0/”转换为地址:名称或服务未知
  • 感谢您向我展示 PQerrorMessage,我现在可以正常连接了!

标签: c postgresql libpq c-api


【解决方案1】:

这是我的问题的解决方案:

我没有使用有效的主机地址。我连接到我自己的本地服务器的正确方法是:

host=localhost

我还删除了 dbname=Project。我收到一条消息,说它不是真正的数据库。我想我不需要在 PQconnectdb 中调用 dbname。

现在,当我使用这些更改运行它时,我得到:

Msg: Connection ok
Disconnected

【讨论】:

  • 在 printf 语句中使用 PQerrorMessage 帮助我调试了我的问题。
【解决方案2】:

试试这个

#include <libpq-fe.h>
#include <stdio.h>
#include <string>
#include <iostream>
void main(){
string m_strHost="127.0.0.1";
string m_strPort="5433";
string m_strUser="postgres";
string m_strPassword="postgres";
string m_strDataBase="postgres";

string strConnection="hostaddr="+m_strHost+" "+"port="+m_strPort+" "+"user="+m_strUser+" "+"password="+m_strPassword+" "+"dbname="+m_strDataBase;
cout <<"\n ctrstring =  "<<strConnection;

char *pcon = const_cast<char*>(strConnection.c_str());
conn = PQconnectdb(pcon);
cout <<"\n";
//conn = PQconnectdb("user=postgres password=postgres dbname=postgres hostaddr=127.0.0.1 port=5433");

// Check to see that the backend connection was successfully made
if (PQstatus(conn) != CONNECTION_OK)
{
    cout<<"Connection to database failed";
    PQfinish(conn);
}else { cout<<"Connection to database - OK\n";}
}

【讨论】:

    猜你喜欢
    • 2020-01-24
    • 1970-01-01
    • 2019-10-08
    • 2017-08-02
    • 2017-03-03
    • 2012-10-10
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    相关资源
    最近更新 更多