在Python中设置数据库连接超时 [英] Set database connection timeout in Python

查看:2843
本文介绍了在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中类似。 p>

感谢您对查询的

解决方案

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



这些行中的某些东西:

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


I'm creating a RESTful API which needs to access the database. I'm using Restish, Oracle, and SQLAlchemy. However, I'll try to frame my question as generically as possible, without taking Restish or other web APIs into account.

I would like to be able to set a timeout for a connection executing a query. This is to ensure that long running queries are abandoned, and the connection discarded (or recycled). This query timeout can be a global value, meaning, I don't need to change it per query or connection creation.

Given the following code:

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()

How can I modify the above code to set a query timeout on it? Will this timeout also apply to connection creation?

This is similar to what java.sql.Statement's setQueryTimeout(int seconds) method does in Java.

Thanks

解决方案

for the query, you can look on timer and conn.cancel() call.

something in those lines:

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

这篇关于在Python中设置数据库连接超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆