我目前正在开发一个 Discord Python 机器人,我会循环遍历 ForumTags 列表,并为每个对象生成一个
INSERT INTO
SQL 语句,以将数据插入 MySQL 数据库。
但是,我想通过将所有这些单独的
INSERT INTO
语句组合到单个查询中来优化我的代码,如下所示:
INSERT INTO guild_support_tags (guild_id, tag_id, tag_name, category) VALUES
(123, 1, "test", "test_category"), (456, 2, "another tag", "test_category2)
这是我当前的代码:
start = time.time()
for tag in forum.available_tags:
await write_query("INSERT INTO guild_support_tags (guild_id, tag_id, tag_name, category) VALUES "
"(:guild_id, :tag_id, :tag_name, :category)",
{"guild_id": interaction.guild_id, "tag_id": tag.id, "tag_name": tag.name,
"category": category})
print(f"loop done after {time.time() - start}")
# from other file - created by myself to execute MySQL statements
# I would like a solution where this part is untouched. But if it can be improved, its okay.
async def write_query(query: str, params: dict) -> None:
async with async_session() as session:
async with session.begin():
await session.execute(text(query), params)
也许了解一下是件好事:我目前在 MySQL 数据库上使用 SQLAlchemy 以及 aiomysql 和 Python3.12。
我发现我仍然可以使用 execute() 函数,并且通过将参数
params
类型从 dict
更改为 dict | list
,它有效。
SQLAlchemy 将检测到这一点并更改其行为以插入所有需要的行。 这种方法允许高效插入而无需循环:
# Prepare the data for the query
query_values: list[dict] = [{"guild_id": interaction.guild_id, "tag_id": tag.id,
"tag_name": tag.name, "category": category}
for tag in forum.available_tags]
# Modify the function to allow "list" and "dict" as type for "params"
async def write_query(query: str, params: dict | list) -> None:
async with async_session() as session:
async with session.begin():
await session.execute(text(query), params)
# execute it
await write_query("INSERT INTO guild_support_tags (guild_id, tag_id, tag_name, category)
VALUES (:guild_id, :tag_id, :tag_name, :category)", query_values)