首页 > 解决方案 > 使用pyhon的动态sql查询形成

问题描述

我是 python 新手,想在 python 中动态形成 SQL 查询。所以尝试下面的示例代码:

empId = 12

query = ''' select  name, ''' +
if empId > 10:
    '''basic_salary'''
else:
    ''' bonus'''
+ ''' from employee '''

print(query)

但是,出现语法错误。有谁知道如何在python中形成动态查询。

标签: sqlpython-3.x

解决方案


您需要指示查询的分配在下一行继续,您可以\在行尾使用 a 来执行此操作。此外,您需要将if语句编写为内联表达式,因为在赋值语句中间if不能有语句:if

empId = 12

query = ''' select  name, ''' + \
        ('''basic_salary''' if empId > 10 else ''' bonus''') + \
        ''' from employee '''

print(query)

输出:

select  name, basic_salary from employee 

如果您有多个条件,您可以query在条件中添加。例如:

empId = 6

query = 'select name, '
if empId > 10:
    query += 'basic_salary'
elif empId > 5:
    query += 'benefits'
else:
    query += 'bonus'
query += ' from employee'

print(query)

输出

select name, benefits from employee

推荐阅读