简体   繁体   English

Python + SQLite:绑定元组列表

[英]Python + SQLite: Bind list of tuples

I have an insert statement with only one parameter 我有一个只有一个参数的插入语句

INSERT OR IGNORE INTO sample (descr) VALUES (?);

And I have a list of tuples 我有一个元组列表

[(a,b), (c,d)]

Now I am using 现在我正在使用

cur.executemany(query, listOfTuples)

Python doesn't like to receive 2 params, and demands only 1. What is the best way to bind all first values from the tuples with this statement? Python不喜欢接收2个参数,而只需要1个。 用此语句绑定元组中所有第一个值的最佳方法是什么?

I've tried something like 我已经尝试过类似

cur.executemany(query, listOfTuples[0])

But now Python thinks I am giving it 4 params. 但是现在Python认为我给了它4个参数。

Use a list comprehension to select just the first value; 使用列表推导仅选择第一个值; using a slice to create new tuples of length 1: 使用切片创建长度为1的新元组

cur.executemany(query, [t[:1] for t in listOfTuples])

Quick demo to show the result of the list comprehension: 快速演示以显示列表理解的结果:

>>> listOfTuples = [('a', 'b'), ('c', 'd')]
>>> [t[:1] for t in listOfTuples]
[('a',), ('c',)]

You can also use a generator expression, which creates the tuple slices on the fly: 您还可以使用生成器表达式,该表达式可动态创建元组切片:

cur.executemany(query, (t[:1] for t in listOfTuples))

It could be that not all database APIs support an iterable and instead expect to be handed something that has a length though. 可能不是所有的数据库API都支持可迭代的,而是希望传递具有一定长度的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM