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:
- 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"
)
- Create a JSON column in the database using the
ALTER TABLE
command.
ALTER TABLE mytable ADD json_column JSON;
- 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()
- 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
More of Python Mysql
- How can I use Python to retrieve data from MySQL?
- How can I connect Python and MySQL?
- How can I troubleshoot a Python MySQL OperationalError?
- How can I use Python and MySQL to generate a PDF?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I use Python and MySQL to create a login system?
- How can I connect Python to a MySQL database using an Xserver?
- How do I access MySQL using Python?
- How do I connect Python to a MySQL database using Visual Studio Code?
- How can I connect to a MySQL database over SSH using Python?
See more codes...