Setting up a connection

The very first thing to do before we can begin working with a database, is actually connect to one. We do this by creating a connection object that will serve as our "handle" on the connection:

	connection Conn("dbname=test");
      

This gives us a connection object called Conn.

The connection constructor here takes one argument, the "connect string." This string may be used to specify which host on the network runs the database backend we wish to connect to, which database we're interested in, which user name we'll be using to log in, etc. Refer to the libpq connect call for a complete definition of what may go into the connect string. In this case we're connecting to a database test residing on the local machine. By default the client will try to connect to a server running on the local machine.

If no connection could be established, the connection constructor may throw an exception immediately; or it may decide to retry the connection later in case the problem is only temporary. In the latter case, an exception may occur at some later point if the problem turns out not to be so temporary after all.

The connection can now act as a "service counter" for our database; your client will use it to perform one or more transactions related to the database.

Connections cannot be copied or assigned. Any attempt to do so will be met with a compiler error.

Caution

As a matter of design, libpqxx™ will not allow you to perform queries on the connection directly. You will need to open a transaction instead.

See the section on transactions below.