JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。MySQL 是一种关系型数据库管理系统,广泛用于存储和管理数据。
MySQL 中的 JSON 数据类型主要有两种:
JSON
:用于存储 JSON 文档。JSONB
(Binary JSON):在某些数据库系统中,如 PostgreSQL,用于存储二进制格式的 JSON 数据,提供更高效的查询和存储。以下是一个使用 Python 和 MySQL 连接器将 JSON 数据插入 MySQL 数据库的示例:
import mysql.connector
import json
# 连接到 MySQL 数据库
db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
cursor = db.cursor()
# JSON 数据
data = {
"name": "John Doe",
"age": 30,
"email": "johndoe@example.com",
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
}
}
# 将 JSON 数据转换为字符串
json_data = json.dumps(data)
# 插入 JSON 数据到 MySQL 表中
sql = "INSERT INTO users (json_data) VALUES (%s)"
cursor.execute(sql, (json_data,))
# 提交事务
db.commit()
# 关闭连接
cursor.close()
db.close()
utf8mb4
,以支持所有 Unicode 字符。通过以上方法,可以有效地解决 JSON 插入 MySQL 过程中遇到的常见问题。
领取专属 10元无门槛券
手把手带您无忧上云