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

iliaden picture iliaden · Aug 10, 2011 · Viewed 54.9k times · Source

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.

Answer

mouad picture mouad · Aug 10, 2011

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

cursor.fetchone()[0]