python-mysqlHow can I use Python to convert MySQL data into JSON format?
To convert MySQL data into JSON format using Python, you can use the json
library and mysql.connector
library. Below is an example of how this can be done:
import mysql.connector
import json
# Establish connection to MySQL
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="yourdatabasename"
)
# Create a cursor object
mycursor = mydb.cursor()
# Execute a query
query = "SELECT * FROM customers"
mycursor.execute(query)
# Fetch all the rows
rows = mycursor.fetchall()
# Convert the rows into JSON
json_data = json.dumps(rows)
# Print the JSON
print(json_data)
Output example
[["John", "Highway 21"], ["Amy", "Mountain 21"]]
The code above consists of the following parts:
import mysql.connector
andimport json
- imports the necessary libraries.mydb = mysql.connector.connect()
- establishes a connection to the MySQL database.mycursor = mydb.cursor()
- creates a cursor object.query = "SELECT * FROM customers"
- creates a query to select all data from thecustomers
table.mycursor.execute(query)
- executes the query.rows = mycursor.fetchall()
- fetches all the rows from the table.json_data = json.dumps(rows)
- converts the rows into JSON.print(json_data)
- prints the JSON data.
Helpful links
More of Python Mysql
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How can I connect Python to a MySQL database using an Xserver?
- How can I connect Python and MySQL?
- How can I retrieve unread results from a MySQL database using Python?
- How can I use Yum to install the MySQLdb Python module?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
- How can I use Python to interact with a MySQL database?
- How do I use Python to authenticate MySQL on Windows?
- How can I use the WHERE IN clause in Python to query a MySQL database?
See more codes...