PQconnectdb返回NULL,为什么?

时间:2012-07-16 10:01:16

标签: postgresql postgresql-9.1

上下文

我刚刚在Lion上安装了postgres 9.1.4,我想在C(libpq)中编写一个简单的客户端来连接PG数据库。

psql -l <​​/ em>表示 postgresDB 拥有一个名为 mydb 的数据库。

psql mydb 说: mydb =#

这是尝试连接到mydb的小程序:

// Server coordinates
const char * keywords[] = {"dbname", "user", NULL};
const char * values[] = {"mydb", "postgresDB", NULL};

// Check server state
analyse_PQpingParams (PQpingParams (keywords, values, 0));

// Connect to the database
PGconn * conn; 
conn = PQconnectdbParams (keywords, values, 0);

// Check if the connection is healthy
analyse_PQstatus (PQstatus (conn));

// Clean exit
PQfinish (conn);
exit (0);

问题

这是程序返回的内容:

analyse_PQpingParams says :
------
The server is running and appears to be accepting connections.
------

analyse_PQstatus says :
------
The state returned was NULL.
------

为什么 conn 对象 NULL

文件说:

请注意,这些函数将始终返回非null对象指针,除非分配PGconn对象的内存可能太少。如果是内存问题,那么 psql 无法连接到我的数据库。所以,文档在这里没有帮助。也许在其他地方?

非常感谢你的回答!

皮尔。

analyse_PQstatus代码:

void analyse_PQstatus (int status) 
{
  cout << "\nanalyse_PQstatus says :" << endl;
  cout << "------" << endl;
  switch (status)
    {
    case CONNECTION_STARTED:
      cout << "Waiting for connection to be made." << endl;
      break;

    case CONNECTION_MADE:
      cout << "Connection OK; waiting to send." << endl;
      break;

    case CONNECTION_AWAITING_RESPONSE:
      cout << "Waiting for a response from the server." << endl;
      break;

    case CONNECTION_AUTH_OK:
      cout << "Received authentication; waiting for backend start-up to finish." << endl;
      break;

    case CONNECTION_SSL_STARTUP:
      cout << "Negotiating SSL encryption." << endl;
      break;

    case CONNECTION_SETENV:
      cout << "Negotiating environment-driven parameter settings." << endl;
      break;
    case 0 :
      cout << "The state returned was NULL" << endl;
      break;
    default :
      cout << "could not analyse this status code : " << status << endl;
    } 
    cout << "------\n" << endl;
} 

1 个答案:

答案 0 :(得分:0)

你能展示analyse_PQstatus功能吗?您是否真的发现conn为NULL或PQstatus(conn)的结果(您传递给函数的结果)是0,即CONNECTION_OK