PostgreSQL 8.3.7 Documentation
Prev | Fast Backward | Chapter 32. ECPG - Embedded SQL in C | Fast Forward | Next

# 32.2. Connecting to the Database Server

One connects to a database using the following statement:

    EXEC SQL CONNECT TO target [AS connection-name] [USER user-name];

The `target` can be specified in the following ways:

- ``dbname`[@`hostname`][:`port`]`

- `tcp:postgresql://`hostname`[:`port`][/`dbname`][?`options`]`

- `unix:postgresql://`hostname`[:`port`][/`dbname`][?`options`]`

- an SQL string literal containing one of the above forms

- a reference to a character variable containing one of the above forms (see examples)

- `DEFAULT`

If you specify the connection target literally (that is, not through a variable reference) and you don't quote the value, then the case-insensitivity rules of normal SQL are applied. In that case you can also double-quote the individual parameters separately as needed. In practice, it is probably less error-prone to use a (single-quoted) string literal or a variable reference. The connection target `DEFAULT` initiates a connection to the default database under the default user name. No separate user name or connection name can be specified in that case.

There are also different ways to specify the user name:

- ``username``

- ``username`/`password``

- ``username` IDENTIFIED BY `password``

- ``username` USING `password``

As above, the parameters `username` and `password` can be an SQL identifier, an SQL string literal, or a reference to a character variable.

The `connection-name` is used to handle multiple connections in one program. It can be omitted if a program uses only one connection. The most recently opened connection becomes the current connection, which is used by default when an SQL statement is to be executed (see later in this chapter).

Here are some examples of `CONNECT` statements:

    EXEC SQL CONNECT TO mydb@sql.mydomain.com;

    EXEC SQL CONNECT TO unix:postgresql://sql.mydomain.com/mydb AS myconnection USER john;

    EXEC SQL BEGIN DECLARE SECTION;
    const char *target = "mydb@sql.mydomain.com";
    const char *user = "john";
    EXEC SQL END DECLARE SECTION;
     ...
    EXEC SQL CONNECT TO :target USER :user;

The last form makes use of the variant referred to above as character variable reference. You will see in later sections how C variables can be used in SQL statements when you prefix them with a colon.

Be advised that the format of the connection target is not specified in the SQL standard. So if you want to develop portable applications, you might want to use something based on the last example above to encapsulate the connection target string somewhere.

Prev | Home | Next
The Concept | Up | Closing a Connection