在Python中设置数据库连接超时

2024-06-05 23:36:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个需要访问数据库的RESTful API。我使用Restish、Oracle和SQLAlchemy。不过,我会尽量将我的问题概括起来,而不考虑Restish或其他web api。

我希望能够为执行查询的连接设置超时。这是为了确保放弃长时间运行的查询,并丢弃(或回收)连接。这个查询超时可以是一个全局值,这意味着,我不需要在每次查询或连接创建时更改它。

给定以下代码:

import cx_Oracle
import sqlalchemy.pool as pool

conn_pool = pool.manage(cx_Oracle)
conn = conn_pool.connect("username/p4ss@dbname")
conn.ping()

try:
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM really_slow_query")
    print cursor.fetchone()
finally:
    cursor.close()

如何修改上述代码以设置查询超时? 此超时是否也适用于连接创建?

这类似于java.sql.Statement的setQueryTimeout(int seconds)方法在java中的作用。

谢谢


Tags: 代码importapiwebrestful数据库sqlalchemyjava
3条回答

对于查询,可以查看timer和conn.cancel()调用。

这句话的意思是:

t = threading.Timer(timeout,conn.cancel)
t.start()
cursor = conn.cursor()
cursor.execute(query)
res =  cursor.fetchall()
t.cancel()

在linux中,请参见/etc/oracle/sqlnet.ora

sqlnet.outbound_connect_timeout= value

还可以选择:

tcp.connect_timeout和sqlnet.expire_time,祝你好运!

您可以考虑在Oracle中设置PROFILEs,以便在每次调用的逻辑读取数和/或每次调用的cpu数达到一定数量后终止查询

相关问题 更多 >