python-mysqlHow do I insert JSON data into a MySQL database using Python?
To insert JSON data into a MySQL database using Python, the following steps can be taken:
- Install the MySQL Connector for Python. This can be done using the command
pip install mysql-connector-python
. - Create a connection to the MySQL database using the
connect()
method. An example of this is shown below:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="passwd",
database="mydatabase"
)
- Create a cursor object using the
cursor()
method, which will allow us to execute SQL commands.mycursor = mydb.cursor()
- Create a JSON string to be inserted into the database.
json_data = { "name": "John", "age": 30, "city": "New York" }
- Convert the JSON string to a Python dictionary using the
json.loads()
method.import json
json_dict = json.loads(json_data)
6. Use the `execute()` method to insert the JSON data into the database.
sql = "INSERT INTO customers (name, age, city) VALUES (%s, %s, %s)" val = (json_dict['name'], json_dict['age'], json_dict['city'])
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
7. Output: `1 record inserted.`
## Helpful links
- https://dev.mysql.com/doc/connector-python/en/connector-python-installation-binary.html
- https://www.w3schools.com/python/python_json.asp
More of Python Mysql
- How can I connect Python to a MySQL database?
- How do I use Python to authenticate MySQL on Windows?
- How can I use Python to retrieve data from MySQL?
- How do I use Python to connect to a MySQL database using XAMPP?
- How can I create a Python MySQL tutorial?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I use Yum to install the MySQLdb Python module?
- How can I use Python and MySQL to generate a PDF?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
- How can I use Python to interact with a MySQL database using YAML?
See more codes...