无法在 "set variable = ?" 语句上使用参数化,但硬编码有效

Cannot use parametrization on "set variable = ?" statement but hardcoding works

我想在建立 JDBC 连接后更改参数 statement_timeout。因此我有以下代码:

PreparedStatement statement = _connection.prepareStatement("set statement_timeout = ?");
statement.setInt(1, (int) _statementTimeout);
statement.execute();

但是在 execute() 这会导致 SQL 异常,清楚地表明我在问号处有语法错误。

org.postgresql.util.PSQLException: ERROR: syntax error at or near ""
  Position: 25

我尝试搜索这个问题,但没有找到任何正确答案。这些页面认为我指的是 UPDATE 子句的 SET

我的问题很简单,为什么参数化不起作用?如果我对值进行硬编码,例如

prepareStatement(String.format("set statement_timeout = %s", _statementTimeout))

一切正常,符合预期。或者在设置变量时使用参数化只是错误的?

使用等效的 function call 应该有效:

prepareStatement("select set_config('statement_timeout', ?, false)");
statement.setString(1, Integer.toString(_statementTimeout));
statement.execute();

请注意,您需要将值作为字符串传递,因为函数的签名是 (text, text, boolean)