psycopg2 : cursor already closed

参考如下的技术贴

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即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值