在try-except块中关闭光标后如何关闭连接?

时间:2019-06-26 12:32:48

标签: python mysql lambda rds

我正在使用RDS实例在Lambda函数(Python 3.6)中执行代码。问题是如果我不这样做,那么conn.close()会增加RDS中的连接数。此后将导致API响应中出现错误[内部服务器错误]。

我们尝试在finally块中尝试,但没有得到下面给出的正确输出。

try:
    conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, port=3268, connect_timeout=30)
except:
    logger.error("ERROR: Unexpected error: Could not connect to MySql instance.")
    sys.exit()
def handler(event, context):
    try:
        with conn.cursor() as cur:
           cur.execute('SELECT * from OrderMaster')
           cur.close()
           return {'statusCode':200,"headers":{"access-control-allow-origin":"{}".format(headers)},"body":json.dumps(out)}
    except Exception as e:
        logger.error("error")
    finally:
        conn.close()

2 个答案:

答案 0 :(得分:0)

我想不出在您的处理程序函数外部打开连接但在其内部关闭连接的原因。 使用处理程序函数内的with语句打开连接。

def handler(event, context):
    try:
        with pymysql.connect(rds_host, user=name, passwd=password, db=db_name, port=3268, connect_timeout=30) as conn
            with conn.cursor() as cur:
               cur.execute('SELECT * from OrderMaster')
               return {'statusCode':200,"headers":{"access-control-allow-origin":"{}".format(headers)},"body":json.dumps(out)}
    except Exception as e:
        logger.error("error")

您也不需要关闭光标,因为您的with语句可以为您完成此操作。连接也是如此。

答案 1 :(得分:0)

def handler(event, context):
    try:
       with pymysql.connect(rds_host, user=name, passwd=password, db=db_name, port=3268, connect_timeout=30) as cur:
          cur.execute('SELECT * from OrderMaster')
          return {'statusCode':200,"headers":{"access-control-allow-origin":"{}".format(headers)},"body":json.dumps(out)}
    except Exception as e:
       logger.error("error") 
    finally: 
       cur.close()