9951 explained code solutions for 126 technologies


python-mysqlHow to use Python to add a JSON column to a MySQL database?


To add a JSON column to a MySQL database using Python, the following steps should be taken:

  1. Establish a connection to the MySQL database using the mysql.connector library.
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="username",
  passwd="password",
  database="mydatabase"
)
  1. Create a JSON column in the database using the ALTER TABLE command.
ALTER TABLE mytable ADD json_column JSON;
  1. Insert the JSON data into the column using the INSERT INTO command.
mycursor = mydb.cursor()

sql = "INSERT INTO mytable (json_column) VALUES (%s)"
val = ('{"name":"John","age":30,"city":"New York"}',)

mycursor.execute(sql, val)
mydb.commit()
  1. Check that the data was successfully inserted by querying the table.
SELECT * FROM mytable;

Output example

+----+------------------------------------+
| id | json_column                        |
+----+------------------------------------+
|  1 | {"name":"John","age":30,"city":"NY"}|
+----+------------------------------------+

Helpful links

Edit this code on GitHub