如何从python中的SQL查询中获取单个结果? [英] How to get a single result from a SQL query in python?

查看:68
本文介绍了如何从python中的SQL查询中获取单个结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 Python 时,是否有一种优雅的方法可以从 SQLite SELECT 查询中获取单个结果?

Is there an elegant way of getting a single result from an SQLite SELECT query when using Python?

例如:

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 并直接获取值?我试过了

is there a way to avoid those nested fors and get the value directly? I've tried

maxVal = cursor[0][0]

没有任何成功.

推荐答案

我想你正在寻找 Cursor.fetchone() :

cursor.fetchone()[0]

这篇关于如何从python中的SQL查询中获取单个结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆