我是一个试图学习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;
}
非常感谢任何输入,谢谢!
想出来了!
我没有使用有效的hostaddr。我把它改为:
host=localhost
我也删除了dbname = Project。当我运行它时,我得到:
Msg: Connection ok
Disconnected
答案 0 :(得分:0)
以下是我的问题的解决方案:
我没有使用有效的hostaddr。我连接到我自己的本地服务器的正确方法是:
host=localhost
我也删除了dbname = Project。我收到一条消息说它不是真正的数据库。我想我不需要在PQconnectdb中调用dbname。
现在,当我使用这些更改运行它时,我得到:
Msg: Connection ok
Disconnected
答案 1 :(得分: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";}
}