如何返回PQXX连接并保存到其他变量


// 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();

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

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

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

相关内容

  • 没有找到相关文章

最新更新