I have written a small program which creates reports in a text file on the behaviours of students. However, I want my program to be able to break the -try- statement if no records are found. How do I do this?
I am writing it in Python and using sqlite3.
You have 3 options, none require
try
:for results that return only a single row, use
cursor.fetchone()
; this returns either the row, orNone
if there were no matches:for multiple rows, just loop over the cursor; if there were no results the loop will not throw an exception, just not iterate:
If you wanted to detect if there were 0 results, you could set a flag variable:
For a smaller set of expected results, you can use
cursor.fetchall()
; this returns an empty list if there were no results:Don't use this to process a large number of rows; just use option #2 for that.
This option does give you the choice to do something else if there were 0 results:
If you have to use
try
, then provoke an exception. For options #1 and #3, all you need to do is indexing:or
For option #2,
next()
will throw aStopIteration
if there is no next result: