与postgres的数据库连接在python语言的服务器中不断断开

问题描述

import psycopg2
from psycopg2 import pool
connection_pool = psycopg2.pool.ThreadedConnectionPool(1,50,user='A',password='S',host='D',port='D',database='AD')

def fetch_data(id):
    try:
        sql = build_sql_query('SELECT * FROM USERS')
        connection = connection_pool.getconn()
        cursor = connection.cursor()
        cursor.execute(sql)
        records = cursor.fetchall()
    except (Exception,psycopg2.Error) as error :
        print ("Error while connecting to PostgreSQL",error)

我不想断开连接。想与postgres建立终身的全球联系。我已经尝试了很多,但如果有的话,请告诉我。

解决方法

在我手中,它不会每次都断开连接。他们只是积累。

你必须这样做:

connection_pool.putconn(connection)

当您完成连接时。也许你认为当它超出范围时应该自动发生,但显然它没有。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...