1

Using Python 3.8.6 & SQL Server Express

cursor.execute("SELECT Output FROM Chat WHERE Input ='"+talk+"';") 
for row in cursor: 
     if row[0] != None:
         print(row[0])
         break
     else:
         print("There is no response")
         break
  • If there is a SQL record the output prints fine
  • If there is no SQL record then nothing prints

I would like the program to print "There is no response" if no record is found in SQL Server.

  • What is the *traceback*, is there an error? You may need to use `getData = cursor.fetchall("SELECT Output...")`. You will get all the data back that way. – de_classified Sep 18 '20 at 02:55
  • what you are expecting is invalid. If the record doesn't matcht the query then it's not included in the output – deadshot Sep 18 '20 at 03:13
  • [SQL Injection](https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work) detected. – Preben Huybrechts Sep 18 '20 at 04:44
  • You can use `len()` in combination with fetchall like @FishingCode suggested, to determine if you have zero records. – Preben Huybrechts Sep 18 '20 at 04:48

1 Answers1

0

Thanks for the feedback.
Using fetchall() and len() as suggested provided the evaluation of an empty SQL query.

records = cursor.fetchall() 
rowCount = len(records) 
  if rowCount == 0: 
     print("There is no response") 

cursor.fetchall() fetches all the rows of a query result. The rows are returned as a list of tuples. Care should be taken if large amounts of data are retrieved into memory. An empty list is returned if there is no record to fetch which allows for evaluation.
len() then evaluates length.