-2

I am using Sqlite3 and Python. Here is some sample code:

       test
-----------------
   amount | date

query = "SELECT SUM (column1) FROM test WHERE date BETWEEN '"+blah+"' AND '"+blah+"'"
c.execute(query)
data = c.fetchone()
if not data:
   amountsum = 0
else:
   amountsum = data[0]

print(amountsum)

The problem is that it only runs else:. If data is NoneType it does not set amountsum to 0 either. How can I make this work?

1 Answers1

1

In this case, data will never be None, due to the aggregating query. SELECT SUM(...) FROM table will always return exactly one row. However, the SUM can be None in SQLite, if there are no rows in the table, so that should be taken into account:

query = "SELECT SUM (column1) FROM test WHERE ..."
c.execute(query)
data = c.fetchone()
amount = data[0] or 0

(A sidenote: you seem to be creating your SQL query using string concatenation, which is a potential SQL injection vulnerability. Consider using parameterized queries instead.)

bereal
  • 32,519
  • 6
  • 58
  • 104
  • So if no rows match the `WHERE` clause, the result would be `[None]`, am I correct? But the result would never be `None` or `[]`. – Fred Larson Oct 19 '20 at 14:04
  • @FredLarson `fetchone()` will return `(None,)`. It's due to the aggregated query. If it was `SELECT * FROM table`, it would return `None`. – bereal Oct 19 '20 at 14:06