连接池用尽了psycopg2

时间:2018-09-05 12:13:13

标签: python pandas psycopg2

我对Postgresql psycopg2有问题。 我收到错误消息:

  

执行异常时出错:连接池已耗尽

我的代码:

from psycopg2 import pool
import pandas.io.sql as sqlio
import pandas as pd
db = pool.ThreadedConnectionPool(5, 100,host=POSTGRES['host'],
database=POSTGRES['database'],user=POSTGRES['username'],
password=POSTGRES['password'],port=POSTGRES['port'])


try:
    sql = "select * from role"  
    data = sqlio.read_sql_query(sql, db.getconn())
    return data.to_json(orient='records')
except Exception as e:
    print "error in executing with exception: ", e
    return pd.DataFrame({'empty' : []})

此请求应仅返回5行,但出现此错误。

您知道我为什么会收到此错误吗?

我的Postgresql数据库(中型实例)部署在公共云上。

提前谢谢

1 个答案:

答案 0 :(得分:2)

似乎您需要在某个时候将连接返回到池中,请参阅:

http://initd.org/psycopg/docs/pool.html#psycopg2.pool.AbstractConnectionPool.putconn

即像这样:

sql = "select * from role"  
try:
    conn = db.getconn()
    try:
        data = sqlio.read_sql_query(sql, conn)
    finally:
        pool.putconn(conn)
    return data.to_json(orient='records')
except Exception as e:
    print "error in executing with exception: ", e
    return pd.DataFrame({'empty' : []})