python AttributeError: ‘NoneType’ object has no attribute ‘open’
在写python关闭数据库连接时,代码报错: AttributeError: ‘NoneType’ object has no attribute ‘open’ 。这是因为 connection
在 finally
块中可能仍然是 None
,而尝试对 None
类型的对象调用 .open
方法会引发此错误。
为了修复这个问题,我们需要更精确地控制 connection
的使用。在 finally
块中,应该确保 connection
既不为 None
也必须是一个有效的连接对象。因此,可以通过检查 connection
是否不为 None
来避免此错误,同时简化 finally
块的处理逻辑。
修改后的正确代码如下:
def get_charge_electric(self, day, bms_pid_system_code, charge_type):
connection = None
cursor = None
try:
connection = pymysql.connect(**self.db_config)
cursor = connection.cursor(pymysql.cursors.DictCursor)
# 判断charge_type是charge_electric还是discharge_electric,并在query替换
if charge_type == 'charge_electric':
query = """
SELECT charge_electric
FROM bigdata_test_electric_day
WHERE day = %s AND bms_pid_system_code = %s
"""
else:
query = """
SELECT discharge_electric
FROM bigdata_test_electric_day
WHERE day = %s AND bms_pid_system_code = %s
"""
cursor.execute(query, (day, bms_pid_system_code))
result = cursor.fetchone()
return result[charge_type] if result else None
except pymysql.MySQLError as e:
print(f"Error: {e}")
return None
finally:
if cursor is not None:
cursor.close()
if connection is not None:
connection.close()