pythonsqlsqlitepython-db-api

How to get a single result from a SQL query in python?


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 fors and get the value directly? I've tried

maxVal = cursor[0][0]

without any success.


Solution

  • I think you're looking for Cursor.fetchone() :

    cursor.fetchone()[0]