【问题标题】:how to return pqxx connection and save into other variable?如何返回 pqxx 连接并保存到其他变量中?
【发布时间】:2015-08-27 08:56:42
【问题描述】:
// DataBaseConn.cpp
#include <iostream>
#include "yaml-cpp/yaml.h"
#include "DatabaseConn.h"

connection DatabaseConn::getConn() {

YAML::Node config = YAML::LoadFile("database.yaml");
std::string psql_user = config["production"]["user"].as<string>();
std::string psql_pass = config["production"]["password"].as<string>();
connection C("dbname=demo user="+ psql_user +" password="+ psql_pass +" hostaddr=127.0.0.1 port=5432");
if (C.is_open()) {
    std::cout << "Opened database successfully: " << C.dbname() << std::endl;
} else {
    std::cout << "Can't open database" << std::endl;
    throw "Database Connection Error";
}
return pqxx::basic_connection<connect_direct>(C);

}

并尝试将连接保存在其他变量中以供进一步使用

 connection conn = DatabaseConn().getConn();

这可能吗?我做错了什么? 我是 C++ 新手。

编译错误:

/usr/local/include/pqxx/basic_connection.hxx:54:40: error: within this context
template<typename CONNECTPOLICY> class basic_connection :
                                    ^
main.cpp: In function ‘int main()’:
main.cpp:20:50: note: synthesized method ‘pqxx::basic_connection<pqxx::connect_direct>::basic_connection(const pqxx::basic_connection<pqxx::connect_direct>&)’ first required here 
     connection conn = DatabaseConn().getConn();

【问题讨论】:

    标签: c++ c++11 libpqxx


    【解决方案1】:

    连接对象可能不可复制或移动,因此不能按值返回。考虑通过 operator new 在堆上分配它并返回一个指向它的指针:

    connection *DatabaseConn::getConn()
    {
        // ...omitted...
        return new pqxx::basic_connection<connect_direct>(C);
    }
    

    调用者负责删除返回的连接。

    【讨论】:

      猜你喜欢
      • 2019-07-28
      • 2021-11-18
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      • 2019-12-14
      • 1970-01-01
      相关资源
      最近更新 更多