首页 > 解决方案 > 如何在 groovy 中处理 PostgreSQL 超时

问题描述

在我的 Groovy 脚本中,我具有以下结构:

def sql = Sql.newInstance(connString, "user", "password", 
"org.postgresql.Driver")

sql.withTransaction {
     sql.withBatch(){}

     sql.withBatch(){}

     sql.withBatch(){}

     .........

}

sql.close()

我想在这里处理超时问题。

但是 Sql API 没有任何方法。

那么我该怎么做呢?我正在使用 PostgreSQL 驱动程序。

我遇到了这个。但我得到错误:

java.sql.SQLFeatureNotSupportedException:方法 org.postgresql.jdbc4.Jdbc4Connection.setNetworkTimeout(Executor, int) 尚未实现。

PS:

int[] modifyCount = sql.withBatch(batchSize, updateQuery) { ps ->
        keyValue.each { k,v ->
            ps.addBatch(keyvalue:k, newvalue:v)
        }
    }

在上面的代码中,当我尝试添加 ps.setQueryTimeout() 时,错误消息说没有定义这样的方法。

标签: postgresqlgroovy

解决方案


可以通过连接属性定义低级超时:

https://jdbc.postgresql.org/documentation/head/connect.html

  • loginTimeout指定等待建立数据库连接的时间。
  • connectTimeout用于套接字连接操作的超时值。
  • socketTimeout用于套接字读取操作的超时值。

这些属性可以在连接 URL 或附加的 Properties 对象参数中指定。

查询超时。连接到数据库后,您可以定义要为每个语句执行的闭包:

sql.withStatement{java.sql.Statement stmt->
    stmt.setQueryTimeout( MY_SQL_TIMEOUT )
}

推荐阅读