ocstat
ocstat

Reputation: 3

Calculate a mean with python sqlite3 using the cursor

I have a database containing a table and I want to compute the mean of a column without importing all of the rows and doing it directly in python; I think doing that would take longer (computation-wise and code-wise) than doing it using sqlite. I figured that the following should work:

cursor.execute('SELECT AVG(column) FROM table')

However, I have no idea how to actually extract the output of this SQL command. I can't find a useful method of the cursor class in the documentation (https://docs.python.org/3/library/sqlite3.html) to help me with this.

Please tell me if what I'm doing makes no sense or is stupid; I have not used SQL before so it might be either of both of the above.

Thank you

Upvotes: 0

Views: 1543

Answers (1)

Z. Bagley
Z. Bagley

Reputation: 9270

Not sure of your other code, but I think you're looking for the .fetchone() method. Something along these lines should work:

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('SELECT AVG(column) FROM table')
print(c.fetchone())

.fetchone() method returns one result, if you're looking to return more than one result from an execute you would use a loop like:

for row in c.execute('SELECT * FROM table')
    print(row)

Upvotes: 2

Related Questions