首页 > 解决方案 > Python SQLite3 [] 和 () 的区别

问题描述

我正在阅读一些 SQLite 文档,但并不真正理解使用 [括号] 和使用 (括号) 之间的区别。

c.execute('INSERT INTO list VALUES(?)', [name])

c.execute('INSERT INTO list VALUES(?)', (name))

c.execute('INSERT INTO list VALUES(?, ?)', ('name', 'age')

像这样的东西可以吗?

c.execute('INSERT INTO list VALUES(?, ?)', [name, age])

标签: pythonsqlite

解决方案


是的,这也有效。它们之间的区别:

cur.execute()parameters参数需要:

  • 使用问号占位符 - 列表,元组,放入查询占位符的可迭代值或值序列。这就是您在上面使用的。
  • 或者,将参数名称映射到它们的值的命名占位符 - 字典。

您可以在查询中使用其中任何一个。副作用很小,但首选元组,因为它们是不可变的并且方法较少。所以 Python 需要更少的资源来创建和使用它们。对于大多数需要序列的方法/函数来说,这是正确的。

>>> # This is the qmark style:
>>> cur.execute("insert into people values (?, ?)", (who, age))
<sqlite3.Cursor object at 0x0000000002C2E3B0>
>>>
>>> # *** this is also qmark style, but with a list of params instead of a tuple of params ***
>>> cur.execute("insert into people values (?, ?)", [who, age])
<sqlite3.Cursor object at 0x0000000002C2E3B0>
>>>
>>> cur.execute('select * from people')
<sqlite3.Cursor object at 0x0000000002C2E3B0>
>>> cur.fetchall()
[('Yeltsin', 72), ('Yeltsin', 72)]
>>>

c.execute('INSERT INTO list VALUES(?)', (name))来自bereal的评论如下

[name]是一个包含一个元素的列表。如果要创建一个包含一个元素的元组,则需要添加一个逗号来表示:(name,). 否则,(name)就是name在查询中。那是一个字符串,它本身是一个可迭代的并且会扩展为字符串中每个字符的序列。

>>> list('Yeltsin')
['Y', 'e', 'l', 't', 's', 'i', 'n']
>>> tuple('Yeltsin')
('Y', 'e', 'l', 't', 's', 'i', 'n')

因此,如果您execute()这样做,它会将字符串视为一个序列,抱怨您传递了太多参数:

>>> cur.execute("insert into people values (?)", (who))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 7 supplied.

只有一个参数的元组的正确方法:

>>> cur.execute("insert into people values (?)", (who,))
<sqlite3.Cursor object at 0x0000000002698A40>
>>>
>>> # or with a list, no comma needed
>>> cur.execute("insert into people values (?)", [who])
<sqlite3.Cursor object at 0x0000000002698A40>
>>>

推荐阅读