On Thu, June 28, 2007 03:57, Fei Liu wrote: > I want a persistent connection, a connection to postgresql database > server I can use throughout the lifetime of my program. As we know, > connecting and disconnecting from a server can be expensive. It seems I > simply cann't do this with libpqxx. For example,
Yes you can! The problem is just a simple misunderstanding about C++ syntax. It looks like you're probably coming from a Java background, so I'll explain on that assumption. > #include <pqxx/pqxx> > class mydbh{ > private: > pqxx::connection c; > public: > mydbh(){ > c = pqxx::connection(""); > } > }; In C++, unlike Java, when you create a variable of object type (such as the member variable "pqxx::connection c;") then you get an instance of the object, not a reference. So you don't need to assign c in your constructor. The object is already there. Also, when you write a constructor in C++, you initialize base-class objects and members with a special syntax. So unlike Java, those constructor calls come *before* the constructor body. So in this case, you'd do: mydbh() : c("") { } Of course, if you're using the empty connection string, you can just use the default constructor for the connection: mydb() : c() {} Which is also what the compiler assumes as the definition for your constructor. So in your example, you can even make things work by leaving out your constructor entirely! This class definition does exactly the same things as your example above (although of course you'll want to add your own member functions): #include <pqxx/pqxx> class mydbh{ pqxx::connection c; }; Done. The connection connects when you create this object. If you want to have a constructor that lets you specify your own connection string, you add: explicit mydbh(const std::string &connstring) : c(connstring) {} The "explicit" keyword says that this is not providing an implicit conversion from string to mydbh. That will help protect you from subtle mistakes in code using your mydbh class. > I simply can't compile this code due to connection class design > decision. Is there a workaround of this problem? Or am I missing > something completely? It has nothing to do with the connection class design. This is a common problem for C++ beginners to run into. Jeroen _______________________________________________ Libpqxx-general mailing list Libpqxx-general@gborg.postgresql.org http://gborg.postgresql.org/mailman/listinfo/libpqxx-general