Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 789
iliaden Avatar asked Aug 10 '11 13:08

iliaden


People also ask

How do you store SQL query results in a variable in Python?

First of all, c. fetchall() retrieves ALL the results from your query, we'll put them in a variable called rows . Then we create a iterator (the thing you tried to do with the while loop) by doing for row in rows . Then we simply print each row.

Which function is used to collect the result of select query in Python?

The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones). The fetchone() method fetches the next row in the result of a query and returns it as a tuple.


2 Answers

Or you could write a wrapper function that, given SQL, returns a scalar result:

def get_scalar_result(conn, sql):     cursor=conn.cursor()     cursor.execute(sql)      return cursor.fetchone()[0] 

I apologize for the possibly less than syntactically correct Python above, but I hope you get the idea.

like image 26
J. Polfer Avatar answered Sep 29 '22 14:09

J. Polfer


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

cursor.fetchone()[0] 
like image 99
mouad Avatar answered Sep 29 '22 14:09

mouad