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,city_list,"id")

错误


'NoneType' object has no attribute 'rollback

请帮忙。提前致谢


智慧大石
浏览 87回答 1
1回答

叮当猫咪

看起来你尝试的第一行可能发生了错误,所以当你到达 except 时,连接仍然是 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()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python