与postgres的c ++连接总是段错误

时间:2015-12-11 01:58:27

标签: c++ postgresql libpq libpqxx

我无法让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 ++编译好,有什么建议吗?

1 个答案:

答案 0 :(得分:0)

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

声明一个未初始化的指针,然后在未初始化的指针上调用一个方法。

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

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