为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

智慧大石 2023-06-13 11:10:01
我正在尝试使用 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请帮忙。提前致谢
查看完整描述

1 回答

?
叮当猫咪

TA贡献1776条经验 获得超12个赞

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


查看完整回答
反对 回复 2023-06-13
  • 1 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信