0

我正在尝试使用 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,city_list,"id")

错误

'NoneType' object has no attribute 'rollback

请帮忙。提前致谢

4

1 回答 1

1

看起来你尝试的第一行可能发生了错误,所以当你到达异常时连接仍然是 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()

于 2020-08-23T03:55:12.630 回答