云数据库 GaussDB-连接数据库

时间:2023-11-01 16:18:27

连接数据库

使用如下语句连接数据库:

EXEC SQL CONNECT TO target [AS connection-name] [USER user-name];
target可以通过如下方法声明,斜体部分为变量,请根据实际情况进行修改:
  • dbname[@hostname][:port]
  • tcp:postgresql://hostname[:port][/dbname][?options]
  • unix:postgresql://hostname[:port][/dbname][?options]
  • 一个包含上述形式之一的SQL字符串
声明连接用户名的方法有以下方式:
  • username/password
  • username SQLIDENTIFIED BY password
  • username USING password

如上所述,参数username以及password可以是一个SQL标识符、一个SQL字符串或一个对字符变量的引用。

connection_name表示连接名,如果一个程序只使用一个连接,则可以省略它。最近打开的连接成为当前连接。

示例:
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"; const char *passwd = "secret"; EXEC SQL END DECLARE SECTION;  ... EXEC SQL CONNECT TO :target USER :user USING :passwd; /* 或者 EXEC SQL CONNECT TO :target USER :user/:passwd; */
  • 最后一种形式引用了字符变量,在宿主变量中将介绍如何在SQL语句中引用C语言变量。
  • 连接目标的格式未在SQL标准中说明,因此若要开发可移植的应用,可使用上述最后一个例子的方法将连接目标字符串封装在某个变量里。
  • 若连接语句中指定了ip-port,则必须指定username/password,该规则由GaussDB Kernel内核通信认证所决定。若不指定ip-port,则通过本地$PGPORT(UDS协议)进行通信。
  • 若客户连接时使用ssl安全协议,则需要使用tcp:postgresql://hostname[:port][/dbname][?options]连接格式,在options选项中配置sslmode=disable\require。
support.huaweicloud.com/centralized-devg-v3-opengauss/gaussdb-12-0212.html