The pg_cnx class
The connection to the database server is maintained through a pg_cnx object.
The simpler way to build a connection is to instantiate a pg_cnx
object and call its connect() method. Its string argument should
contain the same parameters than the libpq
cnx.connect("dbname=mydb host=pgserver port=5433");
Then that pg_cnx object can be used by pg_stream or pg_stmt
classes to issue SQL statements. When the pg_cnx object is destroyed,
the connexion gets implicitly closed.
It is also possible to instantiate a pg_cnx object with an
already opened connection, by passing a PGconn* to its constructor.
A pg_cnx object has boolean parameters, that are set with
pg_cnx::set_option(const char*, bool). The options are:
- prepare_statements: when true, a PREPARE sql command is
issued when a pg_stream is instantiated within that connexion.
This can be changed on a per query basis, and is false by default.
- bind_variables: when true, the query's parameters values
will be passed outside of the SQL text (using the PQexecParams or
PQexecPrepared libpq calls), thus possibly enhancing performance.
When false, the parameters are replaced by their values within the SQL
text (the libpq PQexec call will be used).
This can be changed on a per query basis, see the
pg_stream class for more information. It is false by default.
- nested_transactions: if true, when a new transaction
object is created while already inside a transaction, a SAVEPOINT is
issued to start a subtransaction. See the pg_trans class for more information.
This feature can be used only when connected to PostgreSQL v8.0 or
higher, and the option is false by default.
- pg_cnx (PGconn* conn=NULL)
Constructor. An existing connection previously opened with libpq
can be passed through the conn pointer. Otherwise the connect()
method will have to be called for the connexion to be established with
the database server.
- [virtual] ~pg_cnx()
Destructor. If a connection had been opened with connect(), it is
closed at that time.
- void connect(const char* cnx_string)
Opens a connection with a database server. The cnx_string
argument is passed unmodified to the libpq PQconnectdb() function.
Raises a pg_excpt exception on failure.
- PGconn* conn()
Returns a pointer to the underlying connection structure at the
libpq level. The programmer can use that object to issue direct libpq
- bool set_option(const char* param_name, bool value)
Set the option param_name to value. If param is not in
the list of recognized option names (see "Setting options" above),
a pg_excpt exception is raised.
- bool get_option(const char* param_name) const
Returns the value of the param_name option. Also raises
an exception if param_name is not an option's name.