I have a Python function which receives numerous variables, and builds an SQL query out of them:
def myfunc(name=None, abbr=None, grade=None, ...)
These values should build an SQL query. For that purpose, Those who equal None should be changed to NULL, and those who store useful values should be embraced with 's:
name="'"+name+"\'" if name else 'NULL'
abbr="'"+abbr+"\'" if abbr else 'NULL'
...
Lots of lines here - that's my problem!
...
And than,
query="""INSERT INTO table(name, abbr, ...)
VALUES (%(name)s, %(abbr)s, ...) """ locals()
cur.execute(query)
Is there a nicer, more Pythonic way to change the variable contents according to this rule?
Adam
The best way to form a SQL query is not by string-formatting — the
executemethod of acursorobject takes a query string with placeholders and a sequence (or dict, depending on the exact implementation you have of the DB API) with the values to substitute there; it will then perform the None-to-Null and string-quoting that you require.I strongly recommend you look into that possibility. If you need string processing for some other purpose, however, you could do something like:
and then use dictionary
processedinstead oflocals()for further string-formatting.