【问题标题】:libpqxx: How to reconnect to a Postgresql database after connection process has diedlibpqxx:连接过程结束后如何重新连接到 Postgresql 数据库
【发布时间】:2014-10-01 14:52:19
【问题描述】:

我通过 libpqxx 实例化一个 PostgreSQL 连接。我查询数据库并得到正确的响应。之后我尝试了以下错误案例:在创建 pqxx::connection 实例后,我暂停我的程序,从 Linux 的命令 shell 手动终止 Postgre 的连接进程并恢复程序。它一直持续到它尝试创建新的事务 pqxx::work 并抛出 pqxx::broken_connection。我处理此异常并尝试通过调用 pqxx::connection::activate() 重新连接,但另一个 pqxx::broken_connection 被抛出。如何在不实例化另一个 pqxx::connection 的情况下重新连接到 DB?

附:不禁止重新激活。我使用标准连接类型 -

namespace pqxx
{  
    typedef basic_connection<connect_direct> connection;
}

【问题讨论】:

    标签: c++ linux libpqxx


    【解决方案1】:

    好的,没有人回答。我注意到,在多次连续调用 pqxx::connection::activate 之后手动终止连接背后的进程后,它会重新连接,所以这是我的解决方法。

    class dbconnection : public pqxx::connection
    {
    public:
        dbconnection(std::string options) : pqxx::connection(options) { };
    
        void reconnect()
        {
            static int times = 0;
            try
            {
                times++;
                if(!this->is_open())
                {
                    this->activate();
                }
                times = 0;
            }
            catch(const pqxx::broken_connection & e)
            {
                if(times > 10)
                {
                    times = 0;
                    return;
                }
                this->reconnect();
            }
        };
    };
    

    每次捕获 pqxx::broken_connection 后,我都会调用 dbconnection::reconnect。让我知道您有更好的解决方案吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 2020-05-04
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多