正确处理 Python 中的 NULL 值:字符串与浮点数的转换

正确处理 Python 中的 NULL 值:字符串与浮点数的转换

在 Python 中处理数据库查询结果时,经常会遇到 NULL 值,也就是 Python 中的 None。特别是在将数据转换为 JSON 格式返回时,需要将 None 转换为合适的值,例如空字符串 “” 或数值 0.00。原始代码的问题在于,isinstance 的判断在 item is None 的情况下永远不会执行,因为 None 不是任何类型的实例。

正确处理 NULL 值

以下是经过修改和优化的 format_item 函数,它能正确处理 None 值,并将其转换为合适的类型:

from decimal import Decimal  def format_item(item):     if item is None:         # 根据需要返回默认值:空字符串或 0.00         return 0.00  # 或者 ""     elif isinstance(item, (Decimal, float)):         return float(item)     else:         return str(item)

代码解释:

  1. if item is None:: 首先检查 item 是否为 None。如果是,则直接返回预定义的默认值。根据实际需求,可以选择返回 0.00 (浮点数) 或者 “” (空字符串)。
  2. elif isinstance(item, (Decimal, float)):: 如果 item 不是 None,则检查它是否是 Decimal 或 float 类型的实例。如果是,则将其转换为 float 类型。
  3. else:: 如果 item 既不是 None,也不是 Decimal 或 float 类型,则将其转换为字符串类型。

注意事项:

立即学习Python免费学习笔记(深入)”;

  • None 不是任何类型的实例,所以 isinstance(item, (Decimal, float)) 在 item is None 的情况下永远不会被执行。
  • Decimal 类型需要从 decimal 模块导入。
  • 根据实际需求,选择合适的默认值。如果该字段是数值类型,则选择 0.00 可能更合适;如果该字段是字符串类型,则选择 “” 可能更合适。

应用到数据库查询结果

将上述 format_item 函数应用到数据库查询结果的转换过程中:

正确处理 Python 中的 NULL 值:字符串与浮点数的转换

白瓜AI

白瓜AI,一个免费图文AI创作工具,支持 AI 仿写,图文生成,敏感词检测,图片去水印等等。

正确处理 Python 中的 NULL 值:字符串与浮点数的转换121

查看详情 正确处理 Python 中的 NULL 值:字符串与浮点数的转换

import mysql.connector import os import json import logging from dotenv import load_dotenv from decimal import Decimal  def get_db_password(rds_host):     # Replace this with your actual password retrieval logic     return "your_db_password"  def format_item(item):     if item is None:         # 根据需要返回默认值:空字符串或 0.00         return 0.00  # 或者 ""     elif isinstance(item, (Decimal, float)):         return float(item)     else:         return str(item)  def stored_procedure_call(SP_name, id, entity):     logging.info(f"Fetching DB connection details.")     try:         # Load env file         load_dotenv()         # Create the connection object         conn = mysql.connector.connect(             user=os.getenv('USER_NAME'),             password=get_db_password(os.getenv('RDS_HOST')),             host=os.getenv('RDS_HOST'),             database=os.getenv('DB_NAME'),             port=os.getenv('PORT'))          # Create a cursor         cursor = conn.cursor()     except Exception as error:         logging.error("An unexpected error occurred: {}".format(error))         return {             'statusCode': 500,             'body': json.dumps(f"Error connecting to database: {error}")         }      try:         # Call the stored procedure with the provided ID         cursor.callproc(SP_name, [id, entity])         conn.commit()          result_list = []         for result in cursor.stored_results():             rows = result.fetchall()             for row in rows:                 result_list.append(list(row))                 logging.info(row)          if not result_list:             return {                 'statusCode': 200,                 'body': json.dumps([])             }          result_list_serializable = [list(format_item(item) for item in tup) for tup in result_list]          return {             'statusCode': 200,             'headers': {                 'Content-Type': 'application/json'             },             'body': json.dumps(result_list_serializable)         }      except Exception as e:         logging.error(f"Error executing stored procedure: {e}")         return {             'statusCode': 500,             'body': json.dumps(f"Error executing stored procedure: {e}")         }      finally:         if conn:             cursor.close()             conn.close()

代码解释:

  1. 在 stored_procedure_call 函数中,数据库查询结果 result_list 中的每个元素 item 都会经过 format_item 函数处理。
  2. format_item 函数会将 None 值转换为预定义的默认值,并将其他类型的值转换为字符串或浮点数类型。
  3. 最终,result_list_serializable 包含了经过转换后的数据,可以安全地转换为 JSON 格式。

总结:

通过使用 format_item 函数,可以有效地处理数据库查询结果中的 None 值,并将其转换为合适的类型,从而避免在后续处理过程中出现错误。 确保在处理数据库查询结果时,始终考虑到 NULL 值的存在,并采取适当的措施来处理它们。 这对于确保数据的完整性和应用程序的稳定性至关重要。

mysql word python js json app ai red Python json Float NULL if 字符串 值类型 字符串类型 数据库

上一篇
下一篇