简体   繁体   English

使用 pyhon 的动态 sql 查询形成

[英]dynamic sql query formation using pyhon

I am new to the python and want to form SQL query dynamically in python.so tried below sample code:我是 python 的新手,想在 python 中动态形成 SQL 查询。所以尝试了以下示例代码:

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.有谁知道如何在 python 中形成动态查询。

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:此外,您需要将if语句编写为内联if表达式,因为在赋值语句的中间不能有if语句:

empId = 12

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

print(query)

Output: Output:

select  name, basic_salary from employee 

If you have multiple conditions, you can just add to query in the conditions.如果您有多个条件,您可以在条件中添加到query 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 Output

select name, benefits from employee

#dynamic sql query formation using python #This is for PostgresSQL you can use this for other queries as well: #dynamic sql 使用 python 查询形成#这适用于 PostgresSQL,您也可以将其用于其他查询:

def updateQuery(self,tableName,setFields,setValues,whereFields,whereValues): print("Generating update query started") def updateQuery(self,tableName,setFields,setValues,whereFields,whereValues): print("开始生成更新查询")

querySetfields = None
queryWhereFields = None

# Loop for set fields
for i in range(len(setFields)):
    if querySetfields is None:
        querySetfields=setFields[i]+"='"+setValues[i]+"'"
    else:
        querySetfields=querySetfields+","+setFields[i]+"='"+setValues[i]+"'"

# Loop for whereFields
for i in range(len(whereFields)):
    if queryWhereFields is None:
        queryWhereFields=whereFields[i]+"='"+whereValues[i]+"'"
    else:
        queryWhereFields=queryWhereFields+","+whereFields[i]+"='"+whereValues[i]+"'"

#Form the complete update query
query="UPDATE "+tableName+" SET "+querySetfields+" WHERE "+queryWhereFields

print("Generating update query completed")

return query

print(updateQuery(None,"EMPLOYEE_DETAILS",["EMPI_ID","EMP_LANID","EMP_NAME","EMP_EMAIL"],["A","B","C"],["EMPI_ID","EMP_LANID"],["X","Y","Z"])) print(updateQuery(None,"EMPLOYEE_DETAILS",["EMPI_ID","EMP_LANID","EMP_NAME","EMP_EMAIL"],["A","B","C"],["EMPI_ID","EMP_LANID" ],["X","Y","Z"]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM