Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The json module in Python can be used to encode JSON strings in mysql.connector. Here is an example:

import json
import mysql.connector

# Create a dictionary to be encoded as JSON
data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

# Convert the dictionary to a JSON string
json_data = json.dumps(data)

# Connect to the MySQL database
cnx = mysql.connector.connect(user='username', password='password',
                              host='host', database='database')

# Insert the JSON string into a table
query = "INSERT INTO mytable (json_column) VALUES (%s)"
cursor = cnx.cursor()
cursor.execute(query, (json_data,))
cnx.commit()

# Close the database connection
cursor.close()
cnx.close()

In this example, the json.dumps() function is used to convert the dictionary to a JSON string. The JSON string is then inserted into a MySQL table using a parameterized SQL query. The %s placeholder is used to specify the JSON string as a parameter to the query. The second argument to the cursor.execute() function is a tuple containing the JSON string.