我正在嘗試使用 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()
添加回答
舉報
0/150
提交
取消