在PSycopg2/Postgres上执行查询时展开Timeout

use*_*937 -3 sql postgresql psycopg2

我正在处理需要数小时才能执行的复杂查询.我正在使用PSycopg2

通过阅读这篇文章.我补充说:

 import os.environ
    ['PGOPTIONS'] = '-c statement_timeout=1000000'
Run Code Online (Sandbox Code Playgroud)

现在,我每次都收到错误,执行此查询:

import psycopg2
>>> cnn = psycopg2.connect("dbname=test options='-c statement_timeout=1000'")
>>> cur = cnn.cursor()
>>> cur.execute("select pg_sleep(200000)")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
psycopg2.extensions.QueryCanceledError: canceling statement due to statement timeout
Run Code Online (Sandbox Code Playgroud)

我的问题:如何强制应用程序花费很长时间来处理查询?

Cra*_*ger 6

如果您希望应用程序花费很长时间来处理查询,则必须删除强制它提前终止的语句超时.

去掉:

 import os.environ
    ['PGOPTIONS'] = '-c statement_timeout=1000000'
Run Code Online (Sandbox Code Playgroud)

并在您的连接字符串中删除该options条目.

>>> cnn = psycopg2.connect("dbname=test")
Run Code Online (Sandbox Code Playgroud)

现在,如果您希望保留一般的超时,但仅为此查询覆盖它,那么在查询之前,显式SET statement_timeout地覆盖您设置的默认值:

cur.execute("SET statement_timeout = 0")
cur.execute("select pg_sleep(200000)")
Run Code Online (Sandbox Code Playgroud)

......如果是这样的话你为什么不这么说呢