Issue
I am new to the python and want to form SQL query dynamically in python.so tried below sample code:
empId = 12
query = ''' select name, ''' +
if empId > 10:
'''basic_salary'''
else:
''' bonus'''
+ ''' from employee '''
print(query)
but , getting syntax error. does anyone knows how to form dynamic query in python.
Solution
You need to indicate that the assignment to query continues on the next line, which you can do with a \
at the end of the line. Also, you need to write the if
statement as an inline if
expression as you can't have an if
statement in the middle of an assignment statement:
empId = 12
query = ''' select name, ''' + \
('''basic_salary''' if empId > 10 else ''' bonus''') + \
''' from employee '''
print(query)
Output:
select name, basic_salary from employee
If you have multiple conditions, you can just add to query
in the conditions. For example:
empId = 6
query = 'select name, '
if empId > 10:
query += 'basic_salary'
elif empId > 5:
query += 'benefits'
else:
query += 'bonus'
query += ' from employee'
print(query)
Output
select name, benefits from employee
Answered By - Nick
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.