参考如下的技术贴

python - psycopg2 : cursor already closed - Stack Overflowhttps://stackoverflow.com/questions/35651586/psycopg2-cursor-already-closed[Solved] Python psycopg2 : cursor already closed - Code RedirectI am using psycopg2 2.6.1. I have a bunch of queries that I need to execute in sequence.conn = psycopg2.connect(database=redshift_database, user=redshift_user, ...https://coderedirect.com/questions/516674/psycopg2-cursor-already-closed

给出我的伪代码:

import psycopg2
def connect_postgre():
    _pg_database = get_config_value('postgre', 'pg_database')
    _pg_user = get_config_value('postgre', 'pg_user')
    _pg_password = get_config_value('postgre', 'pg_password')
    _pg_host = get_config_value('postgre', 'pg_host')
    _pg_port = get_config_value('postgre', 'pg_port')
    _pg_schema = get_config_value('postgre', 'pg_schema')

    _pg_obj = None
    _pg_obj = psycopg2.connect(database=_pg_database, user=_pg_user, password=_pg_password, host=_pg_host, port=_pg_port, options="-c search_path=" + _pg_schema)
    try:
        _pg_obj.cursor().execute('select 1')
        # print('psycopg2 Connect')
        return _pg_obj
    except psycopg2.OperationalError:
        print('psycopg2 it could not connect!')
        _pg_obj = psycopg2.connect(database=_pg_database, user=_pg_user, password=_pg_password, host=_pg_host,
                                   port=_pg_port, options="-c search_path=" + _pg_schema)
        _pg_obj.cursor().execute('select 1')
        return _es_obj
    except psycopg2.InterfaceError:
        print('psycopg2 it could not connect!')
        _pg_obj = psycopg2.connect(database=_pg_database, user=_pg_user, password=_pg_password, host=_pg_host,
                                   port=_pg_port, options="-c search_path=" + _pg_schema)
        _pg_obj.cursor().execute('select 1')
        return _pg_obj

 

 psycopg2总会关闭,那么就在try-catch中,再次连接postgre即可。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐