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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-06-30 19:25:31 +0000
Seen: 17 times
Last updated: Jun 30 '23
How can a web application be developed to send distinct emails upon clicking the SUBMIT button?
What is the process of developing two databases in a Django application using docker-compose?
How can Flask and SQLAlchemy be used to connect to a MySQL database?
How can multiple queries be merged into a single stored procedure in MySQL?
What does "waiting for handler commit" mean in relation to the slow writes experienced in MySQL 8?
How can Spring Boot and Mysql be utilized for CRUD operations?