I have a postgres sql statement like so in python:
sql= """delete
from {table}
where person = '{Person}'
AND name= '{Name}'
AND sale= '{Sale}'""".format(table=TABLE,Person=PERSON,Name=NAME,Sale=SALE)
I am trying to account for NULLs in the WHERE clause. I want to do something like this:
where person=Person if person is not None else person is Person
AND <continue same expression for other fields>
Is there a way to incorporate that?
One way would be to create something like this:
sql="delete
from {table}
where " Person if Person is not None else person is Person "
AND "...<same expression>
Was wondering if there was a cleaner way of doing this?
CodePudding user response:
Let the database connector do your substitution.
where = []
vals = []
for k,v in ("person",Person),("name",Name),("sale",Sale):
if v:
where.append(f"{k} = %s")
vals.append(v)
sql= f"DELETE FROM {TABLE} WHERE " (" AND ".join(where))
conn.execute( sql, vals )