要将JSON数据存入MySQL数据库,您需要执行以下步骤:
JSON
数据类型来存储JSON数据。例如:CREATE TABLE my_table (
id INT AUTO_INCREMENT PRIMARY KEY,
json_data JSON
);
mysql-connector-python
库来连接数据库:import mysql.connector
cnx = mysql.connector.connect(
host="your_host",
user="your_user",
password="your_password",
database="your_database"
)
cursor = cnx.cursor()
INSERT INTO
语句将其插入到表中。例如:json_data = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
json_data_str = json.dumps(json_data) # 将JSON对象转换为字符串
query = "INSERT INTO my_table (json_data) VALUES (%s)"
cursor.execute(query, (json_data_str,))
cnx.commit()
cursor.close()
cnx.close()
这样,您就将JSON数据成功存入了MySQL数据库。如果需要查询存储的JSON数据,可以使用JSON_EXTRACT()
函数。例如:
SELECT JSON_EXTRACT(json_data, '$.name') as name FROM my_table;