如何从Python中的SQL查询中获取单个结果?
使用 Python 时,是否有一种优雅的方式从 SQLite SELECT 查询获取单个结果?
例如:
conn = sqlite3.connect('db_path.db')
cursor=conn.cursor()
cursor.execute("SELECT MAX(value) FROM table")
for row in cursor:
for elem in row:
maxVal = elem
有没有办法避免那些嵌套的 for
并直接获取值?我尝试过
maxVal = cursor[0][0]
但没有成功。
Is there an elegant way of getting a single result from an SQLite SELECT query when using Python?
for example:
conn = sqlite3.connect('db_path.db')
cursor=conn.cursor()
cursor.execute("SELECT MAX(value) FROM table")
for row in cursor:
for elem in row:
maxVal = elem
is there a way to avoid those nested for
s and get the value directly? I've tried
maxVal = cursor[0][0]
without any success.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我认为您正在寻找 Cursor.fetchone() :
I think you're looking for Cursor.fetchone() :
请小心,接受的答案可能会导致
TypeError
!由于
fetchone()
文档:对于某些 SQL 查询
cursor.fetchone()[0]
可能会变成None[0]
,从而导致引发TypeError
异常。获取第一行或
None
的更好方法是:first_row = next(cursor, [None])[0]
如果 SQL 查询为空,
next
将使用默认值[None]
并从该列表中获取第一个元素,而不会引发异常。Be careful, accepted answer might cause
TypeError
!Due to
fetchone()
documentation:So with some SQL queries
cursor.fetchone()[0]
could turn intoNone[0]
which leads to raisingTypeError
exception.Better way to get first row or
None
is:first_row = next(cursor, [None])[0]
If SQL query is empty,
next
will use default value[None]
and get first element from that list without raising exceptions.或者,您可以编写一个包装函数,在给定 SQL 的情况下,返回一个标量结果:
对于上面的 Python 语法可能不太正确,我深表歉意,但我希望您明白这一点。
Or you could write a wrapper function that, given SQL, returns a scalar result:
I apologize for the possibly less than syntactically correct Python above, but I hope you get the idea.
如果您没有使用内置的
cursor.fetchone
pysqliteIf you're not using pysqlite which has the built in
cursor.fetchone
序列解包可用于提取标量值来自结果元组。
如果有多行,则通过迭代游标(或cursor.fetchall):
或者如果结果集中只有一行,则使用cursor.fetchone:
在这两种情况下
result
之后的尾随逗号将元素从单元素元组中解压出来。这与更常见的情况相同,只是元组只有一个元素:
Sequence unpacking can be used to extract the scalar value from the result tuple.
By iterating over the cursor (or
cursor.fetchall
)if there are multiple rows:Or using
cursor.fetchone
if there is a single row in the resultset:In both cases the trailing comma after
result
unpacks the element from the single-element tuple. This is the same as the more commonly seenexcept the tuples only have one element:
select count(*) from ... groupy by ...
返回None
而不是0
,因此
fetchone()[0]
会导致异常。所以
select count(*) from ... groupy by ...
returnsNone
instead of0
,so
fetchone()[0]
would lead to an exception.Therefore
或者你可以尝试:
cursor.execute("SELECT * FROM table where name='martin'")
or you can try :
cursor.execute("SELECT * FROM table where name='martin'")