0

语境

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

psql -l表示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

文件说什么:

请注意,这些函数将始终返回一个非空对象指针,除非内存太少甚至无法分配 PGconn 对象。如果是内存问题,则psql无法连接到我的数据库。因此,文档在这里没有帮助。也许在其他地方?

非常感谢您的回答!

皮埃尔。

analysis_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;
} 
4

1 回答 1

0

你能展示一下analyse_PQstatus功能吗?你真的发现它conn是 NULL 还是PQstatus(conn)(这是你传递给函数的)结果是 0,即CONNECTION_OK

于 2012-07-16T10:08:00.920 回答