使用模块 psycopg2 的 PostgreSQL 接口错误 "connection already closed"

PostgreSQL Interface error "connection already closed" using module psycopg2

我使用以下 lambda 函数连接到 PostgreSQL 数据库。我只能执行一次查询,第二次执行时,会出现如下界面错误。

错误

{   "errorMessage": "cursor already closed",   "errorType": "InterfaceError",   "stackTrace": [
    "  File \"/var/task/my_lambda.py\", line 30, in handler\n    cursor.execute(query)\n"   ] }

函数日志

START RequestId: e2a1d17e-48e5-4fa8-bd43-80a27658491a Version: $LATEST
[ERROR] InterfaceError: cursor already closed
Traceback (most recent call last):
  File "/var/task/my_lambda.py", line 30, in handler
    cursor.execute(query)
END RequestId: e2a1d17e-48e5-4fa8-bd43-80a27658491a

Lambda 函数代码

import sys
import logging
import psycopg2
import json
import os

# rds settings
rds_host  = os.environ.get('RDS_HOST')
rds_username = os.environ.get('RDS_USERNAME')
rds_user_pwd = os.environ.get('RDS_USER_PWD')
rds_db_name = os.environ.get('RDS_DB_NAME')

logger = logging.getLogger()
logger.setLevel(logging.INFO)

try:
    conn_string = "host=%s user=%s password=%s dbname=%s" % \
                    (rds_host, rds_username, rds_user_pwd, rds_db_name)
    conn = psycopg2.connect(conn_string)
    cursor = conn.cursor()
except:
    logger.error("ERROR: Could not connect to Postgres instance.")
    sys.exit()

logger.info("SUCCESS: Connection to RDS Postgres instance succeeded")

def handler(event, context):

    query = "select count(*) as active_sessions from pg_stat_activity where state = 'active' AND pid <> pg_backend_pid() and state <> 'idle'"
    cursor.execute(query)
    results = cursor.fetchone()
    cursor.close()
    conn.close()
    print(results)

我也尝试过使用其他查询,但它给了我同样的错误。

@Philippe 提到的评论解决了这个问题。

move the try block in def handler(event, context)