1

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

2 回答 2

1

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

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

host=localhost

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

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

Msg: Connection ok
Disconnected
于 2013-10-02T00:50:18.527 回答
0

试试这个

#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";}
}
于 2016-02-20T06:24:30.130 回答