到postgres的c++连接总是segfault



我无法让libpqxx使用基本查询。它总是出错。我目前正在使用一个类来促进连接。

//nearestLoc.h
class databaseConnection{
public:
    databaseConnection();
    ~databaseConnection();
    void SetConnection();
    void Disconnect();
    pqxx::result query();
    void SetCredentials();
    void SetSqlString(std::string queryString);
private:
    pqxx::connection *conn;
    std::string strSQL;
    std::string username;
    std::string pass;
    std::string host;
};
//nearestLoc.cpp
#include <cstdlib>
#include <string>
#include <pqxx/pqxx>
#include <iostream>
#include "nearestLoc.h"
using namespace std;
using namespace pqxx;
void databaseConnection::SetConnection(){
        try{
            string tot = string("dbname=xxxx") + string(" user=")+username+ string(" password=")+pass+ string(" host=")+host + string(" port=9000");
        pqxx:connection *conn = new connection(tot);
        }
        catch(const std::exception &e){
            std:cerr << e.what() << std::endl;
        }
    }
void databaseConnection::Disconnect(){
        conn->disconnect();
    }
pqxx::result databaseConnection::query(){
        pqxx:work txn(*conn);
        pqxx::result res= txn.exec(strSQL);
        return res;
    }
void databaseConnection::SetCredentials(){
    this->username= std::getenv("PGUSER");
    this->pass= std::getenv("PGPASSWORD");
    this->host = std::getenv("PGHOST");
}
void databaseConnection::SetSqlString(std::string &queryString){
    this->strSQL = queryString;
}

int main(int argc, char **argv) =
    std::string strque = "SELECT * FROM test LIMIT 5";
    databaseConnection* pdatabase;
    pdatabase->SetSqlString(strque);
    pdatabase->SetCredentials();
    pdatabase->SetConnection();
    pqxx::result sites = pdatabase-> query();
    std::cout
            <<"ID"<<"t"
            <<"Station_id"<<"t"
            <<std::endl;
    std::cout
            <<"The top 5 closest sites are"<<std::endl;
    for(pqxx::result::const_iterator row = sites.begin(); row != sites.end(); ++row){
        std::cout
            <<row["id"].as<int>() <<"t"
            <<row["station_id"].as<int>() <<"t"
            <<std::endl;
    }
    return 0;
}

我只是想弄点东西跑起来玩。用g++编译很好,有什么建议吗?

databaseConnection* pdatabase;
pdatabase->SetSqlString(strque);

您声明了一个未初始化的指针,然后调用了一个对未初始化指针的方法。

这是你的问题。你可能想写这个:

databaseConnection* pdatabase=new databaseConnection;
pdatabase->SetSqlString(strque);

相关内容

  • 没有找到相关文章

最新更新