python链接mysql超过最大默认连接时间_在Python中设置数据库连接超时

1586010002-jmsa.png

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值