我在 Python 中使用 psycopg2 执行长时间查询时遇到问题。 当查询时间超过 180 秒时,脚本执行会挂起很长时间。
我使用 Python 3.4.3
和 psycopg2 2.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>
有谁知道如何解决这个问题? 谢谢。
最佳答案
您可能在某处设置了语句超时。尝试为单个语句将其关闭:
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'
)
关于python - 查询时间过长时 psycopg2 游标挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32286164/