python - 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])
解决方案
是的,这也有效。它们之间的区别:
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>
>>>
推荐阅读
- django - 我在打开页面时遇到错误:''TemplateDoesNotExist at /seller2/''
- c# - 检查表达式 C# 中的平衡括号
- java - 找到最长的连续交替序列
- sql - 如何从分组行中提取值到 Oracle SQL 中的特定列?
- python - 使用图像掩码创建 matplotlib 多边形补丁
- python - 如何在 python 中使用 asyncio 运行并发操作?
- scala - 在scala中将Boolean类型转换为Int
- flutter - 在 null 上调用了 getter 'auth'。接收方:null 尝试调用:auth
- python - Django:在处理外键和外键模型中的多对多字段时,我被管理寄存器卡住了
- python-3.x - 在对象上放置尺寸