代码之家  ›  专栏  ›  技术社区  ›  oneself

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

  •  11
  • oneself  · 技术社区  · 15 年前

    我正在创建一个需要访问数据库的RESTfulAPI。我使用的是restish、oracle和sqlacalchemy。但是,我会尽量将我的问题概括起来,而不考虑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.Script的SqQueQu超时(int秒)方法类似。

    谢谢

    4 回复  |  直到 12 年前
        1
  •  13
  •   Dmitry Khrisanov    14 年前

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

    这些行中的一些内容:

    t = threading.Timer(timeout,conn.cancel)
    t.start()
    cursor = conn.cursor()
    cursor.execute(query)
    res =  cursor.fetchall()
    t.cancel()
    
        2
  •  3
  •   athspk RNJ    12 年前

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

    sqlnet.outbound_connect_timeout= value

    还可以选择:

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

        3
  •  0
  •   Gary Myers    15 年前

    你可以看看设置 PROFILE 在Oracle中,在进行一定数量的逻辑读取和/或CPU读取后终止查询。

        4
  •  -3
  •   Mark Harrison    15 年前

    系统报警超时

    下面介绍如何使用操作系统timout来完成此操作。它是通用的,适用于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!!