我写了一个小程序,它在文本文件中创建关于学生行为的报告。但是,如果没有找到记录,我希望我的程序能够打破-try-语句。我该怎么做?
我用Python编写它并使用sqlite3。
答案 0 :(得分:2)
您有3个选项,无需try
:
对于只返回一行的结果,请使用cursor.fetchone()
;这将返回行,如果没有匹配则返回None
:
result_row = cursor.fetchone()
if result_row:
# there was a result
多行,只需循环遍历游标;如果没有结果,循环不会抛出异常,只是不迭代:
for row in cursor:
# do something with `row`
# nothing will happen if there were 0 results
如果要检测是否有0结果,可以设置标志变量:
has_results = False
for row in cursor:
has_results = True
# do something with `row`
if not has_results:
raise ValueError('No results for that query')
对于较小的预期结果,您可以使用cursor.fetchall()
;如果没有结果,则返回一个空列表:
rows = cursor.fetchall()
for row in rows:
# do something with `row`
# nothing will happen if there were 0 results
不要用它来处理大量的行;只需使用选项#2。
如果结果为0,则此选项可让您选择执行其他操作:
rows = cursor.fetchall()
if not rows:
raise ValueError('No results for that query')
如果 使用try
,则会引发异常。对于选项#1和#3,您需要做的就是建立索引:
result_row = cursor.fetchone()
try:
result_column = result_row[0]
except TypeError:
# no result, `result_row` was `None`
或
rows = cursor.fetchall()
try:
first_row = rows[0]
except IndexError:
# no results, `rows` was an empty list
对于选项#2,如果没有下一个结果,next()
会抛出StopIteration
:
try:
first_row = next(cursor)
except StopIteration:
# no results, nothing to iterate over