返回

python-使用psycopg2模块出现PostgreSQL接口错误“;“连接已关闭”;

发布时间:2022-03-10 18:41:54 377
# node.js

我有下面的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)

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

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像