要將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;