1. Installation
pip install mysql-connector-python
2. Insert JSON format data in the database
import import json from datetime import datetime # Create a database connectiondb = ( host="localhost", # MySQL server address user="root", # username password="123456", # password database="test", # Database name port="3307" # Port) # Create a cursor object to execute SQL queriescursor = () # Read JSON file and parse it into Python dictionarywith open('./data/goods_2025', 'r', encoding='utf-8') as file: goods = (file) # Convert dictionary to JSON stringgoods_json = (goods, ensure_ascii=False) # datedate = '2025-02-12' # Execute SQLsql = "INSERT INTO goods (content, date) VALUES (%s, %s)" val = (goods_json, date) (sql, val) # Submit transaction() # Close cursor and database connection() ()
3. Database query json format data
import import json from datetime import datetime # Create a database connectiondb = ( host="localhost", # MySQL server address user="root", # username password="123456", # password database="test", # Database name port="3307" # Port) # Create a cursor object to execute SQL queriescursor = () sql = "SELECT * FROM goods WHERE date = %s" val = ('2025-02-12',) (sql, val) # Get query resultsresult = () # traverse the results and print themfor row in result: print(row) # Get product information (json format)goods = (row[1]) # Submit transaction() # Close cursor and database connection() ()
This is the article about Python implementing the storage of json format data in Mysql database. For more related content for Python json storage to Mysql, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!