首页 > 编程问答 >如何在 Python 中对多行使用单个 INSERT INTO 语句?

如何在 Python 中对多行使用单个 INSERT INTO 语句?

时间:2024-07-26 04:40:35浏览次数:9  
标签:python mysql mariadb sql-insert

我目前正在开发一个 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)

也许最好知道:我目前使用 SQLAlchemy|| |与 aiomysql Python3.12 MariaDB 数据库上。 database.


你可以通过将所有值元组构建为列表,然后使用单个 executemany 调用将它们一次性插入来实现。

start = time.time()
values = []
for tag in forum.available_tags:
    values.append((interaction.guild_id, tag.id, tag.name, category))

await write_query("INSERT INTO guild_support_tags (guild_id, tag_id, tag_name, category) VALUES (:guild_id, :tag_id, :tag_name, :category)", values)

print(f"loop done after {time.time() - start}")


# 来自其他文件 - 由我自己创建以执行 MySQL 语句
# 我希望这个部分不受影响地得到一个解决方案。但如果可以改进,也可以。
async def write_query(query: str, params) -> None:
    async with async_session() as session:
        async with session.begin():
            await session.executemany(text(query), params)

这段代码首先构造一个 values 列表,其中包含每个 ForumTag 的元组。然后,它使用 executemany 方法用单个查询将所有值插入数据库。这比在循环中执行单独的 INSERT 语句要高效得多。

另外,请注意,你不需要在 write_query 函数中将 params 作为字典传递。你可以直接传递值列表或元组,因为 executemany 会处理迭代。

标签:python,mysql,mariadb,sql-insert
From: 78795318

相关文章

  • 双 for 循环的 Pythonic 方式
    我有以下代码:importnumpyasnpepsilon=np.array([[0.,0.00172667,0.00071437,0.00091779,0.00154501],[0.00128983,0.,0.00028139,0.00215905,0.00094862],[0.00035811,0.00018714,0.,0.00029365,0.00036993......
  • 在 matplotlib 中绘制一个字符串函数 // 将 str 解释为 python 代码?
    我正在创建一个RPN计算器,尝试绘制用户给出的函数。例如,如果用户输入"xsin3*plot"我希望它绘制sin(x)*3其代码如下。注意:问题在ifprompt=="plot"userInputX=""#userInputXisalwaysreplacedbefore......
  • Python (Pebble) - 超时功能。当 TimeoutError 发生时,获取从 iterable 传递给函数的值
    我正在尝试在Pebble中设置工作超时(基本上有效)frompebbleimportProcessPoolfrommultiprocessingimportProcess,Pool,cpu_countimporttimedeftest_fn(randomNumberFromList):#print(f'Beginngingforthisnumber:{randomNumberFromList}')ifr......
  • 为什么在 Python 上使用正则表达式组功能会给出不同的输出
    importrestring1="aaabaa"zusuchen="aa"#1m_start=re.finditer(fr'(?=({zusuchen}))',string1)results=[(match.start(1),match.end(1)-1)formatchinm_start]forzinresults:print(z)print("Now#2:"......
  • 如何在python3中找到文件的长度?
    我的第一个.py:defcreate_file(file_name):list=["ab","cd","ef"]foriinlist:withopen(file_name,"a+")asinput_file:print("{}".format(i),file=input_file)我的第二个.py:fromfirstimport......
  • 哪种 python 日志记录风格是推荐的或标准的?
    我是Python新手。介于以下2个选项之间。对于python来说,推荐哪种风格或者更好?logging.info(f"Won'tsavemodelasscoreisbelow0,score:{score}")logging.info("Won'tsavemodelasscoreisbelow0,score%s",score)我个人更喜欢第二种方法。在Python......
  • MySQL查询性能优化
    避免使用SELECT*:只选择必要的列可以减少数据传输量和处理时间。避免使用OR和NOTIN:使用OR和NOTIN会导致全表扫描,影响查询性能。使用LIMIT分页:使用LIMIT分页可以避免一次性返回大量数据‍。使用EXPLAIN查看执行计划:可以通过查看执行计划了解SQL的执行情况。优化WHERE条件:尽可......
  • python 协程 自定义互斥锁
    最近在用python的一款异步web框架sanic搭建web服务,遇到一个需要加特定锁的场景:同一用户并发处理订单时需要排队处理,但不同用户不需要排队。如果仅仅使用asyncwithasyncio.Lock()的话。会使所有请求都排队处理。1importasyncio2importdatetime34lock=asyncio.L......
  • Python 获取tiktok视频评论回复数据 api接口
    TIKTOKapi接口爬取tiktok视频评论回复数据详细采集页面如图https://www.tiktok.com/@dailymail/video/7329872821990182190?q=neural%20link&t=1706783508149请求APIhttp://api.xxxx.com/tt/video/info/comment/reply?video_id=7288909913185701125&comment_id=7294900......
  • Shopee虾皮api python获取虾皮购物平台的商品数据信息 数据采集
    虾皮购物(英语:Shopee)是一个电商平台,总公司设在新加坡,归属于SeaGroup(之前称之为Garena),该企业于2009年由李小冬(ForrestLi)创办。虾皮购物于2015年初次在新加坡推出,现阶段已拓展到马来西亚、泰国、印度尼西亚、越南和菲律宾。虾皮购物为全球华人地区的客户提供线上购物和销售......