Python 当查询时间过长时,psycopg2游标挂起
我在Python中使用psycopg2执行长时间查询时遇到问题。 当查询时间超过180秒时,脚本执行会挂起很长时间 我使用Python 当查询时间过长时,psycopg2游标挂起,python,python-3.x,psycopg2,Python,Python 3.x,Psycopg2,我在Python中使用psycopg2执行长时间查询时遇到问题。 当查询时间超过180秒时,脚本执行会挂起很长时间 我使用python3.4.3和psycopg2.6.1 以下是重现该问题的示例: import psycopg2 cnn = psycopg2.connect( database='**********', user='**********', password='**********', host='**********', port=5
python3.4.3
和psycopg2.6.1
以下是重现该问题的示例:
import psycopg2
cnn = psycopg2.connect(
database='**********',
user='**********',
password='**********',
host='**********',
port=5432,
)
print("Connected")
cursor = cnn.cursor()
seconds = 5
print("Sleep %s seconds"%seconds)
cursor.execute("SELECT pg_sleep(%s);"%seconds)
print("Exit.")
当查询耗时5秒时,脚本工作正常:
$python3 /tmp/test.py
Connected
Sleep 5 seconds
Exit.
但当秒数约为180秒或更大时,行cursor.execute
挂起,下面的指令永远不会执行:
import psycopg2
cnn = psycopg2.connect(
database='**********',
user='**********',
password='**********',
host='**********',
port=5432,
)
print("Connected")
cursor = cnn.cursor()
seconds = 180
print("Sleep %s seconds"%seconds)
cursor.execute("SELECT pg_sleep(%s);"%seconds)
print("Exit.")
以下是一个输出:
$python3 /tmp/test.py
Connected
Sleep 5 seconds
<Never exit>
$python3/tmp/test.py
有联系的
睡眠5秒钟
有人知道如何解决这个问题吗?
谢谢。您可能在某个地方设置了语句超时。尝试为单个语句关闭它:
cursor = cnn.cursor()
seconds = 180
# Turn statement_timeout off for the next query
cursor.execute("SET statement_timeout = 0")
print("Sleep %s seconds"%seconds)
cursor.execute("SELECT pg_sleep(%s);"%seconds)
print("Exit.")
如果这样做有效,请更改默认设置(无论您在何处定义),或仅更改您的连接:
cnn = psycopg2.connect(
database='**********',
user='**********',
password='**********',
host='**********',
port=5432,
options='-c statement_timeout=0'
)
但是如果达到语句超时,是否应该引发
QueryCanceledError
或InternalError
,因为它会终止查询?