CONNECT TO connection_target [ AS connection_name ] [ USER connection_user_name ] CONNECT TO DEFAULT CONNECT connection_user_name DATABASE connection_target
connection_target以下列形式之一指定连接的目标服务器。
通过 TCP/IP 连接
通过 Unix 域套接字
通过 TCP/IP 连接
包含上述形式之一的一个值
类型char[]或VARCHAR[]的主变量,它包含上述形式之一的一个值
用于该连接的一个可选标识符,这样可以在其他命令中引用它。这可以是一个 SQL 标识符或者一个主变量。
用于数据库连接的用户名。
使用 user_name/password、 user_name IDENTIFIED BY password或者 user_name USING password之一,这个参数也能指定用户名和口令.
用户名和口令可以是 SQL 标识符、字符串常量或者主变量。
按 libpq 的定义使用所有默认连接参数。
这里是一些指定连接参数的变体:
EXEC SQL CONNECT TO "connectdb" AS main; EXEC SQL CONNECT TO "connectdb" AS second; EXEC SQL CONNECT TO "unix:postgresql://200.46.204.71/connectdb" AS main USER connectuser; EXEC SQL CONNECT TO "unix:postgresql://localhost/connectdb" AS main USER connectuser; EXEC SQL CONNECT TO 'connectdb' AS main; EXEC SQL CONNECT TO 'unix:postgresql://localhost/connectdb' AS main USER :user; EXEC SQL CONNECT TO :db AS :id; EXEC SQL CONNECT TO :db USER connectuser USING :pw; EXEC SQL CONNECT TO @localhost AS main USER connectdb; EXEC SQL CONNECT TO REGRESSDB1 as main; EXEC SQL CONNECT TO AS main USER connectdb; EXEC SQL CONNECT TO connectdb AS :id; EXEC SQL CONNECT TO connectdb AS main USER connectuser/connectdb; EXEC SQL CONNECT TO connectdb AS main; EXEC SQL CONNECT TO connectdb@localhost AS main; EXEC SQL CONNECT TO tcp:postgresql://localhost/ USER connectdb; EXEC SQL CONNECT TO tcp:postgresql://localhost/connectdb USER connectuser IDENTIFIED BY connectpw; EXEC SQL CONNECT TO tcp:postgresql://localhost:20/connectdb USER connectuser IDENTIFIED BY connectpw; EXEC SQL CONNECT TO unix:postgresql://localhost/ AS main USER connectdb; EXEC SQL CONNECT TO unix:postgresql://localhost/connectdb AS main USER connectuser; EXEC SQL CONNECT TO unix:postgresql://localhost/connectdb USER connectuser IDENTIFIED BY "connectpw"; EXEC SQL CONNECT TO unix:postgresql://localhost/connectdb USER connectuser USING "connectpw"; EXEC SQL CONNECT TO unix:postgresql://localhost/connectdb?connect_timeout=14 USER connectuser;
这里是一个展示使用主变量指定连接参数的例子程序:
int main(void) { EXEC SQL BEGIN DECLARE SECTION; char *dbname = "testdb"; /* 数据库名 */ char *user = "testuser"; /* 连接用户名 */ char *connection = "tcp:postgresql://localhost:5432/testdb"; /* 连接字符串 */ char ver[256]; /* 存储版本字符串的缓冲区 */ EXEC SQL END DECLARE SECTION; ECPGdebug(1, stderr); EXEC SQL CONNECT TO :dbname USER :user; EXEC SQL SELECT version() INTO :ver; EXEC SQL DISCONNECT; printf("version: %s\n", ver); EXEC SQL CONNECT TO :connection USER :user; EXEC SQL SELECT version() INTO :ver; EXEC SQL DISCONNECT; printf("version: %s\n", ver); return 0; }