You can use the func.json_merge
function from SQLAlchemy to merge JSON values within a column in MySQL. Here's an example:
from sqlalchemy import create_engine, Column, Integer, JSON, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('mysql+pymysql://user:password@host/dbname')
Session = sessionmaker(bind=engine)
Base = declarative_base()
class MyTable(Base):
__tablename__ = 'mytable'
id = Column(Integer, primary_key=True)
json_data = Column(JSON)
# Create a session
session = Session()
# Merge two JSON values within a column
result = session.query(func.json_merge(MyTable.json_data, '{"key": "value"}')).filter(MyTable.id == 1).one()
# Commit the changes
session.commit()
In this example, json_data
is a column in the mytable
table that contains JSON data. The func.json_merge
function is used to merge the existing JSON data with the new data ('{"key": "value"}'
) for the row with id
equal to 1. The one()
method is used to retrieve the result as a single row. Finally, the changes are committed to the database using session.commit()
.
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: 2022-09-27 11:00:00 +0000
Seen: 15 times
Last updated: Nov 28 '21
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?
Retrieve all rows in which two IDs appear for the first time.
What are the benefits of choosing sqlalchemy.types instead of sqlalchemy.dialects.mssql?
How can records be counted from a category that is retrieved through another PHP and SQL query?