python - 查询时间过长时 psycopg2 游标挂起

标签 python python-3.x psycopg2

我在 Python 中使用 psycopg2 执行长时间查询时遇到问题。 当查询时间超过 180 秒时,脚本执行会挂起很长时间。

我使用 Python 3.4.3psycopg2 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/

相关文章:

python - Pandas:聚合列的值

python - round() 根据参数的数量返回不同的结果

python - 循环遍历字典键以根据输入获取值

python - psycopg2:使用什么 page_size

python - python 中带引号的分隔符游标 copy_from

python - python(scipy)曲线拟合的奇怪结果

python - django 管理员权限 - 可以编辑用户但不能编辑他的权限 - 怎么做?

python - Django 查询集 : filter by the value of another field

django - 在 Windows 中为 django 安装 postgresql

python - 为连续 Action 空间实现强化(Humanoid-v2)?