如何从字典中选择多行(执行多行选择)

1 投票
3 回答
2853 浏览
提问于 2025-04-15 16:59

我正在使用Python和它的MySQLdb模块,想知道能不能像“selectmany”那样从一个元组、字典或列表中进行条件查询。

类似于这样:

cursor.executemany("""SELECT * FROM customers WHERE name= %(name)s""",[d.__dict__ for d in data])

selected_rows = cursor.fecthall()

用这种方法进行删除、更新或插入操作都很顺利:

cursor.executemany("""UPDATE customers SET item = %(item)s WHERE name = %(name)s""",[d.__dict__ for d in data])

3 个回答

0

executemany 主要是用来插入数据或更新数据的。根据我的经验,它不太适合用来查询数据,因为它通常只会返回最后一组参数的结果。

2

我还没用过 executemany 这个方法,但我想知道它是不是可以用来做 SELECT 查询的。那这样做怎么样

... where name in (...)

而不是

... where name = ...

然后插入一个包含你 data 字典键的元组呢?

3

你可以使用“WHERE IN”这个SQL语法,比如说:

SELECT * FROM customers WHERE name IN ('john', 'mary', 'jane');

撰写回答