python-mysqlHow do I insert JSON data into a MySQL database using Python?
To insert JSON data into a MySQL database using Python, you need to use the json
module to convert the JSON data into a Python dictionary, and then use the MySQL Connector/Python
to insert the data into the MySQL database.
The following example code will demonstrate how to do this:
import mysql.connector
import json
# Load JSON data into Python dictionary
with open('data.json') as json_file:
data = json.load(json_file)
# Connect to MySQL database
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="mydatabase"
)
# Create cursor object
mycursor = mydb.cursor()
# Insert data into database
for record in data:
sql = "INSERT INTO mytable (name, address) VALUES (%s, %s)"
val = (record['name'], record['address'])
mycursor.execute(sql, val)
# Commit changes to database
mydb.commit()
# Close connection to database
mydb.close()
The code above does the following:
- Imports the
mysql.connector
andjson
modules. - Loads the JSON data into a Python dictionary.
- Connects to the MySQL database.
- Creates a cursor object.
- Inserts the data into the database.
- Commits the changes to the database.
- Closes the connection to the database.
Helpful links
More of Python Mysql
- How do I use Python to update multiple columns in a MySQL database?
- How can I access MySQL using Python?
- How can I connect to MySQL using Python?
- How can I convert data from a MySQL database to XML using Python?
- How can I use a while loop in Python to interact with a MySQL database?
- How do I use a Python variable in a MySQL query?
- How do I use Python to show the MySQL processlist?
- How can I escape a string for use in a MySQL query in Python?
- How do I format a date in MySQL using Python?
- ¿Cómo conectar Python a MySQL usando ejemplos?
See more codes...