Connection to Postgres Database using libpqxx
Asked Answered
S

3

7

I am using libpqxx to connect to a postgres database by creating a class.

class databaseConnection
{
public:
    pqxx::connection* conn;
    void SetConnection(){
        conn=new pqxx::connection(
            "username=temp "
            "host=db.corral.tacc.utexas.edu "
            "password=timelione "
            "dbname=temp");

    }

    void Disconnect(){
        conn->disconnect();
    }

    pqxx::result query(std::string strSQL){
        //SetConnection();
        pqxx::work trans(*conn,"trans");

        pqxx::result res=trans.exec(strSQL);

        trans.commit();
        return res;
    }
};

int main()
{
    databaseConnection* pdatabase;
    pdatabase->SetConnection();
    return 0;
}

I am getting error that says

terminate called after throwing an instance of 'pqxx::broken_connection' 
what(): invalid connection option "database"

Can anyone help me out?

Thanks

Spondaic answered 14/10, 2011 at 5:44 Comment(1)
@Spondaic has Daniel's answer helped you? If so please accept it. I'm faced with similar problems and if you don't accept it, most of us new users won't know if this is a solution or not. After all, he's taken the time to help you and you ought to say thanks in the least.Gitlow
N
14

pgxx::connection(const PGSTD::string&) is basically a wrapper around libpq's PQconnectdb() function, so the supported connection parameter keywords are the same as for libpq.

The parameter key word for the PostgreSQL user name to connect as is user, not username. Perhaps correcting that will fix the problem.

Also, in your sample code, pdatabase is an uninitialized pointer. You could either allocate a databaseConnection object on the stack with:

databaseConnection database;
database.SetConnection();

or use new to heap-allocate a databaseConnection object:

databaseConnection* pdatabase = new databaseConnection();
pdatabase->SetConnection();

But you need to pick one.

Nutmeg answered 14/10, 2011 at 14:44 Comment(0)
C
6

if you try like this

try
{
    conn = new pqxx::connection(
    "username=temp "
    "host=db.corral.tacc.utexas.edu "
    "password=timelione "
    "dbname=temp");
}
catch (const std::exception &e)
{
    std::cerr << e.what() << std::endl;
}

it catches the exception about connection string:

invalid connection option "username"
Craquelure answered 11/4, 2014 at 19:20 Comment(0)
D
0

You might also need to add port=5432 to your connection string.

Despotism answered 11/9, 2013 at 23:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.