sql - 使用pyhon的动态sql查询形成
问题描述
我是 python 新手,想在 python 中动态形成 SQL 查询。所以尝试下面的示例代码:
empId = 12
query = ''' select name, ''' +
if empId > 10:
'''basic_salary'''
else:
''' bonus'''
+ ''' from employee '''
print(query)
但是,出现语法错误。有谁知道如何在python中形成动态查询。
解决方案
您需要指示查询的分配在下一行继续,您可以\
在行尾使用 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
推荐阅读
- python-3.x - 在 3D 矩阵中沿单个轴滚动不同量
- reactjs - Apollo 查询未触发 useEffect
- r - 从R中的样本形成组
- python - 使用 Python 从 XML 中读取/提取数据
- arrays - 当数组长度为 0 时解析数组中的元素(MongoDB、React、Axios)
- javascript - 如何制作反应倒数计时器
- unit-testing - 在颤振项目中运行飞镖单元测试
- javascript - Javascript 似乎没有通过引用传递对象
- module - Discord.JS Purge.js 命令问题
- navigation - 如何在简单的 SwiftUI 应用中有效地使用导航链接?