1

我正在尝试创建一个可以访问 PostgreSQL 数据库的程序。问题是我不断得到一个

警告:已经有一个事务在进行中

消息,程序很快退出。我是否需要在需要时关闭并重新打开连接,或者我可以解决问题并在整个程序中重复使用相同的连接?

    int i = 0;
    std::string spassw = "";
    std::string suname = "";

    theconn = NULL;

    // Make a connection to the database
    theconn = PQconnectdb("user=postgres password=changeme dbname=database hostaddr=127.0.0.1    port=5432");

    // Check to see that the backend connection was successfully made
    if ( PQstatus(theconn) != CONNECTION_OK )   {

        std::cout << "Connection to database failed.\nPress any key to continue.\n";
        PQfinish(theconn);
        getchar();
        exit(1);
     }

    PGresult *res  = PQexec(theconn, "BEGIN");

    if (PQresultStatus(res) != PGRES_COMMAND_OK)    {

        printf("BEGIN command failed");
        PQclear(res);
        PQfinish(theconn);
        std::cout << "Goodbye.\n";
        getchar();
        exit(1);
    }

    // Clear result
    PQclear(res);

    res = PQexec(theconn, "DECLARE emprec CURSOR FOR select * from dbtable");

    if (PQresultStatus(res) != PGRES_COMMAND_OK)    {

        printf("DECLARE CURSOR failed\n");
        PQclear(res);
        PQfinish(theconn);
        std::cout << "Goodbye.\n";
        getchar();
        exit(1);
     }

    PQclear(res);
    res = PQexec(theconn, "FETCH ALL in emprec");

    if (PQresultStatus(res) != PGRES_TUPLES_OK) {

        printf("FETCH ALL failed");
        PQclear(res);
        PQfinish(theconn);
        std::cout << "Goodbye.\n";
        getchar();
        exit(1);
    }

    for ( i = 0; i < PQntuples(res); i++ )    {

        std::string suname = PQgetvalue( res, i, 0 );
        std::string spassw = PQgetvalue( res, i, 1 );

        if( pname == suname && pword == spassw )    {

        res = PQexec( theconn, "COMMIT");
        PQclear(res);

        res = PQexec(theconn, "CLOSE emprec" );
        PQclear(res);

        // End the transaction
        res = PQexec(theconn, "END");

        // Clear result
        PQclear(res);
        return true;
        }

    }

    res = PQexec( theconn, "COMMIT");
        PQclear(res);

    res = PQexec(theconn, "CLOSE emprec");
    PQclear(res);

    // End the transaction
    res = PQexec(theconn, "END");

    // Clear result
    PQclear(res);


    return false;
}
4

2 回答 2

4

这里有一个提示:您可以在应用程序的整个执行过程中使用单个连接,但您需要注意事务。您收到的警告是由于正在进行的交易,因此请确保您正确提交和关闭交易。由于我不是 C++ 程序员,因此我无法为您提供有关您的 C++ 代码的建议,但看起来您的问题不是特定于语言的,而是概念性的。否则,我深表歉意。

于 2013-01-04T11:23:21.840 回答
0

由于代码有一个BEGIN启动事务的,它应该有一个(并且只有一个)匹配COMMIT,或END,但不能同时有。

原因是它END实际上是 的同义词COMMIT手册是这样说的:

该命令是相当于 COMMIT 的 PostgreSQL 扩展。

鉴于您的代码当前是如何在光标关闭时组织的,出现以下情况:

   res = PQexec( theconn, "COMMIT");
        PQclear(res);

应该被删除。

于 2013-01-04T15:29:12.570 回答