12

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

谢谢

4

4 回答 4

16

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

这些行中的一些东西:

t = threading.Timer(timeout,conn.cancel)
t.start()
cursor = conn.cursor()
cursor.execute(query)
res =  cursor.fetchall()
t.cancel()
于 2010-06-04T17:54:41.323 回答
4

在 linux 中查看 /etc/oracle/sqlnet.ora,

sqlnet.outbound_connect_timeout= value

也有选择:

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

于 2012-09-27T05:40:30.883 回答
0

您可以查看在 Oracle 中设置PROFILE以在一定数量的 logical_reads_per_call 和/或 cpu_per_call 之后终止查询

于 2010-03-03T23:02:40.720 回答
-3

系统警报超时

以下是如何使用操作系统超时来执行此操作。它是通用的,适用于 Oracle 以外的东西。

import signal
class TimeoutExc(Exception):
    """this exception is raised when there's a timeout"""
    def __init__(self): Exception.__init__(self)
def alarmhandler(signame,frame):
    "sigalarm handler.  raises a Timeout exception"""
    raise TimeoutExc()

nsecs=5
signal.signal(signal.SIGALRM, alarmhandler)  # set the signal handler function
signal.alarm(nsecs)                          # in 5s, the process receives a SIGALRM
try:
    cx_Oracle.connect(blah blah)             # do your thing, connect, query, etc
    signal.alarm(0)                          # if successful, turn of alarm
except TimeoutExc:
    print "timed out!"                       # timed out!!
于 2010-03-11T10:38:24.470 回答