psycopg2-'NoneType'对象没有属性'rollback'

问题描述

我正在尝试从pyspark代码中使用psycopg2从Postgresql表中删除记录。但是我出错了。不知道出什么问题了。预先感谢

def delete_records(table,city_list,key):
    connection = None
    try: 
        connection = psycopg2.connect(host=host,database=db,user=user,password=password)
        cursor = connection.cursor()
        delete_query = "Delete from " +table+ " where "+key+" in "+ str(tuple(city_list))
        cursor.execute(delete_query)
        connection.commit()
        logger.debug("Record deleted successfully")
    except (Exception,psycopg2.DatabaseError) as error :
        logger.error("%s transction error Reverting all other operations of a transction ",error)
        connection.rollback()
    finally:
        if connection is not None:
            cursor.close()
            connection.close()
            logger.debug("Postgresql connection is closed")

delete_records(table_name,"id")

错误

'nonetype' object has no attribute 'rollback

请帮助。预先感谢

解决方法

在尝试的第一行中似乎可能发生了错误,因此当您到达除外时,连接仍然为None。

就像您在评论中提到的那样,将if connection is not None:添加到except块听起来不错。

您可能想弄清楚记录器对错误的评价,以便您进行故障排除,所以您可能想要这样的事情:

except (Exception,psycopg2.DatabaseError) as error :
        logger.error("%s transction error Reverting all other operations of a transction ",error)
        if connection is not None:
            connection.rollback()