在打开连接的属性中设置 statement_timeout

set statement_timeout in properties on opening connection

我想在打开连接时使用 statement_timeout 连接参数。

我已经通过执行 SET statement_timeout to 5000 as 语句成功测试了这个参数,但我希望在打开连接时提供它。

目前我有以下方法(简化):

public Connection openConnection() {
    
    try {
      Driver driver = (Driver) Class.forName("org.postgresql.Driver").newInstance();
      return driver.connect("jdbc:postgresql://localhost:15432/postgres", getProperties());
    } catch (Exception exp) {
      throw new RuntimeException(String.format("Unable to connect to JDBC with additional connection properties.", exp);
    }
  }

private Properties getProperties() {
    Properties properties = new Properties();
    properties.put("statement_timeout", "5000");
    return properties;
  }

但是即使查询SELECT pg_sleep(6)(这个查询至少需要6000ms)也没有异常发生。

这可能吗?因为在 Chapter 3. Initializing the Driver 上我只发现了另外三个超时:loginTimeoutconnectTimeoutsocketTimeout。它们与我有某种关系吗?

根据the documentation,你应该使用options参数:

  • options = String

Specify 'options' connection initialization parameter.

The value of this property may contain spaces or other special characters, and it should be properly encoded if provided in the connection URL. Spaces are considered to separate command-line arguments, unless escaped with a backslash (\); \ represents a literal backslash.

此引用的 options 参数记录在 the PostgreSQL documentation:

options

Specifies command-line options to send to the server at connection start. For example, setting this to -c geqo=off sets the session's value of the geqo parameter to off. Spaces within this string are considered to separate command-line arguments, unless escaped with a backslash (\); write \ to represent a literal backslash. For a detailed discussion of the available options, consult Chapter 19.

所以你应该将options参数设置为

-cstatement_timeout=5000