PyMySQL JSON 数据处理:Python 与 MySQL 交互
你是否在 Python 开发中遇到过 MySQL JSON 字段处理的难题?当需要存储复杂结构数据时,传统关系型字段总是显得力不从心。本文将带你掌握 PyMySQL 中 JSON 数据的完整交互方案,从基础存储到高级查询,让你轻松应对各类 JSON 数据场景。
JSON 数据存储基础
在开始使用 PyMySQL 处理 JSON 数据前,我们需要先了解 MySQL 的 JSON 数据类型。MySQL 从 5.7 版本开始支持原生 JSON 类型,提供了高效的 JSON 数据存储和查询能力。使用 PyMySQL 操作 JSON 数据的核心在于理解 Python 数据结构与 MySQL JSON 格式之间的转换机制。
基本数据插入
使用 PyMySQL 插入 JSON 数据非常简单,只需将 Python 字典或列表直接作为参数传递给 SQL 语句。PyMySQL 会自动处理基本的类型转换,将 Python 数据结构转换为 MySQL 可接受的 JSON 格式。
import pymysql
from pymysql.cursors import DictCursor
# 连接数据库
connection = pymysql.connect(
host='localhost',
user='your_username',
password='your_password',
db='test_db',
charset='utf8mb4',
cursorclass=DictCursor
)
try:
with connection.cursor() as cursor:
# 创建包含 JSON 字段的表
create_table_sql = """
CREATE TABLE IF NOT EXISTS user_profiles (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
preferences JSON NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""
cursor.execute(create_table_sql)
# 插入 JSON 数据
insert_sql = "INSERT INTO user_profiles (name, preferences) VALUES (%s, %s)"
# Python 字典会自动转换为 JSON 格式
user_preferences = {
"theme": "dark",
"notifications": {"email": True, "push": False},
"favorite_features": ["search", "analytics", ],
: {: , : }
}
cursor.execute(insert_sql, (, user_preferences))
connection.commit()
:
connection.close()

