如何从python中的SQLite查询中获取单个结果?

2024-06-28 19:13:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在使用Python2.7时,是否有一种从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

有没有办法避免那些嵌套的fors并直接获取值?我试过了

maxVal = cursor[0][0]

没有任何成功。


Tags: path方法inforexecutedbsqliteconnect
3条回答

我想你在找Cursor.fetchone()

cursor.fetchone()[0]

或者,您可以编写一个包装函数,该函数在给定SQL的情况下返回标量结果:

def get_scalar_result(conn, sql):
    cursor=conn.cursor()
    cursor.execute(sql)

    return cursor.fetchone()[0]

我为上面可能不太符合语法的Python道歉,但我希望您能明白这一点。

如果您不使用内置的pysqlite cursor.fetchone

cursor.execute("select value from table order by value desc limit 1")

相关问题 更多 >