Python SQLite query returns None

2.9k Views Asked by At

The following SQLite query returns 3:

SELECT MAX(depth) FROM mpitree WHERE child = 2

But this code evaluates to None:

def ancestors_depth(self):
    self.cursor.execute("SELECT MAX(depth) FROM mpitree WHERE child = 2");
    return self.cursor.fetchone()[0]

Why is that ?

2

There are 2 best solutions below

0
On

You should store the result of you query I think:

SQL_QUERY = "SELECT MAX(depth) FROM mpitree WHERE child = 2"

def ancestors_depth(self):
    result = self.cursor.execute(SQL_QUERY)
    return result.fetchone()[0]
0
On

All right, I found the problem. My code was called in a unit test. In this unit test, at first I wrote a test case that populated the database (which was working). Then I added a test for the query. But because tests are executed in alphanumerical order, the test that was querying the database was being executed BEFORE the databases was populated.

Thank you for your help.