Updated on 2024-05-07 GMT+08:00

Connecting to a Database

Connect to a database.

EXEC SQL CONNECT TO target [AS connection-name] [USER user-name];
The target can be declared using the following methods. The italic part is a variable. Change it based on the actual situation.
  • dbname[@hostname][:port]
  • tcp:postgresql://hostname[:port][/dbname][?options]
  • unix:postgresql://hostname[:port][/dbname][?options]
  • An SQL string containing one of the above forms
There are also different ways to specify the username:
  • username/password
  • username SQLIDENTIFIED BY password
  • username USING password

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

connection_name indicates the connection name. If a program uses only one connection, you can omit it. The most recently opened connection becomes the current connection.

Example:
#include <stdlib.h>
EXEC SQL CONNECT TO mydb@sql.mydomain.com;  

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

EXEC SQL BEGIN DECLARE SECTION; 
/* The values of target, user, and passwd must be read from environment variables or configuration files. Environment variables need to be configured as required. If no environment variable is used, a character string can be directly assigned. */
const char *target = getenv("EXAMPLE_TARGET_ENV"); 
const char *user = getenv("EXAMPLE_USERNAME_ENV"); 
const char *passwd = getenv("EXAMPLE_PASSWD_ENV"); 
EXEC SQL END DECLARE SECTION;  
... 
EXEC SQL CONNECT TO :target USER :user USING :passwd; 
/* or EXEC SQL CONNECT TO :target USER :user/:passwd; */

For details about the complete example, see the connection syntax example in CONNECT.

  • In the last form, character variables are referenced. For details about how to reference C variables in SQL statements, see Host Variables.
  • The format of the connection target is not described in the SQL standard. Therefore, to develop a portable application, you can use the method in the last example to encapsulate the connection target string into a variable.
  • If ip-port is specified in the connection statement, username and password must be specified. This rule is determined by the GaussDB Kernel communication authentication. If ip-port is not specified, the local $PGPORT (UDS) is used for communication.
  • If the SSL protocol is used for connection, run the tcp:postgresql://hostname[:port][/dbname][?options] command and set sslmode to disable\require in options.