No records need to exit

Currently, in the sql query i need to exit in python if no records exist.

def table_details(con, ctry, clt, cate)
cur = conn.cursor()
name = {}
cur.execute(""" select * from table where and a.client = %s and a.category_code=%s""",(ctry, clt, cate)
for row in cur :
     names[row[0]  = 1
return names

table_details = table_details(conn, ctry, clt, cate)

If no records from the query need to exit the code.

What exactly does “exit the code” mean? And what difficulty are you encountering? For example, can you write code that tells you that there are no records?

The code won’t run as written because:

  • Line 1 is missing a final colon
  • Lines 2-7 aren’t indented.
  • Line 4 is missing a final closing parenthesis.
  • Line 6 is missing a closing bracket.

It’s usually a better idea for the function to raise an exception (or in this case, simply return an empty list) and let the caller decide if exiting the script is warranted. That said, wherever you decide to exit the script, simply call sys.exit. For example,

import sys

def table_details(con, ctry, clt, cate):

if not (details := table_details(conn, ctry, clt, cate)):
    sys.exit(1)  # Non-zero exit status indicates an error or failure
    # Or pass a string argument, which produces an exit status of 1
    # and prints the argument to standard error
    # sys.exit("No records found")


How about something like:

class NoRowsException(Exception):
for row in cur:
if no_rows:
    raise NoRowsException