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

标签 python database oracle cx-oracle python-db-api

我正在创建一个需要访问数据库的 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 中的作用。

谢谢

最佳答案

对于查询,您可以查看计时器和 conn.cancel() 调用。

这些行中的内容:

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

关于python - 在 Python 中设置数据库连接超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2374079/

相关文章:

python - 为什么 Python 3 找不到已安装的包(例如 BeautifulSoup4)?

database - Access 的替代方法

oracle - 替换oracle中的无效字符(通过编辑dmp文件)

python - 如何使用 scons 构建任意食谱?

python - grok 学习 : python course, 向后打印

sql-server - 数据老化技术

Ruby - 数据库的日期时间

java - 如何提高大型文本文件的数据加载性能

oracle - 将 MS SQL 函数转换为 Oracle 函数会引发错误

python - 在 BaseProxy 上调用方法时如何有效地使用 asyncio?