python - MySQL 使用列表推导式插入

标签 python mysql list list-comprehension executemany

我一直在尝试转换我的大部分 mysqlclient使用列表推导式执行要在一行中完成的命令。以下代码片段就是一个示例:

def org(conn, cursor, target_org=None, target_sid=None):
    try:
        if target_sid is not None:
            target_org = [{"sid": target_sid}]
        cursor.executemany(
            "INSERT INTO `Orgs` (`sid`) VALUES (%s);",
            [[Org['sid']] for Org in target_org])
        conn.commit()

...

但是,如果我想要一个需要填充多列的 MySQL 查询,例如

"INSERT INTO `Citizens`(`Handle`,`Org`,`Role`,`Rank`,`Visibility`,`Stars`,`Type`)VALUE(%s,%s,%s,%s,%s,%s,%s)"

如何实现列表理解,接收由列表组成的列表member,其中每个成员的数据与上面的示例一样使用executemany命令?

例如,要仅获取 Handle 列,它看起来像这样

[Mem['handle'] for Mem in member]
# (cursor.executemany must always have a list as second argument)

成员示例:

[{'roles': [], 'rank': 'No SCB account', 'type': 'main', 'stars': 2, 'visibility': 'visible', 'sid': 'imperium', 'handle': 'freakyeagle'}, {'roles': [], 'rank': 'Fleet Member', 'type': 'main', 'stars': 1, 'visibility': 'visible', 'sid': 'imperium', 'handle': 'cadimus'}, {'roles': [], 'rank': 'Fleet Member', 'type': 'main', 'stars': 1, 'visibility': 'visible', 'sid': 'imperium', 'handle': 'belleal'}]

最佳答案

您可以将映射与 executemany 一起使用。插值将根据您的字典进行。由于您的 target_org 是带有键“sid”的字典列表 所以你可以做类似的事情:

cursor.executemany( "INSERT INTO Orgs (sid) VALUES (%(sid)s);", target_org) 

我认为这也适用于你的第二个问题。

参见:https://www.python.org/dev/peps/pep-0249/#paramstyle对于 python db-api 中的参数

关于python - MySQL 使用列表推导式插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33569503/

相关文章:

python - 如果列表中的一个条目的键包含另一列中的字符串,则选择该条目

python - 使用 python 脚本登录 azure cli 时出现问题

python - 将 python mockito 与 python unittest 集成

python - 在元组列表中查找最小值、最大值

Python 请求模块 - Google App Engine

MySQL 从左连接开始对列进行排序

C# - 通过 LAN 远程连接到 XAMPP 数据库

iPhone 和 MySQL

python - 按值对元组排序,当值相等时使用列表

python - 在列表中的元素之间添加元素