|PostgreSQL 8.4.22 Documentation|
|Prev||Fast Backward||Chapter 32. ECPG - Embedded SQL in C||Fast Forward||Next|
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:
an SQL string literal containing one of the above forms
a reference to a character variable containing one of the above forms (see examples)
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 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 firstname.lastname@example.org; EXEC SQL CONNECT TO unix:postgresql://sql.mydomain.com/mydb AS myconnection USER john; EXEC SQL BEGIN DECLARE SECTION; const char *target = "email@example.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.