gpt4 book ai didi

python - 在 python 中传递 le 或 ge 符号

转载 作者:行者123 更新时间:2023-11-29 13:54:59 26 4
gpt4 key购买 nike

我希望之前没有人问过这个问题,我不确定要使用什么关键字。

假设我想编写一个可以采用小于或等于查询语句的函数...

import MySQLdb

def query1(date,le):
'''
query1('2013-01',<= )
>>> 10
'''

query = '''
select *
from table
where number {x} 1
and date = {dt}
'''.format(dt=date,x=le)

cursor.execute(query)
rslt = cursor.fetchall()

return rslt

那么最好的方法是什么?

最佳答案

您可以将比较运算符作为字符串传递给您的函数:

query1('2013-01', '<=')

这会将运算符的字符串插入到查询中,结果

select * 
from table
where number <= 1
and date = 2013-01

请注意,通过插入字符串直接构建 SQL 查询是 SQL 注入(inject)的潜在向量。如果您允许用户提供自己的日期字符串,则用户可能会注入(inject)一些 SQL 代码并运行恶意代码。查看查询参数化以获取更多信息。

如果你想防范 SQL 注入(inject),你应该执行如下操作。允许的运算符列表已仔细列入白名单,因此只能使用有效且安全的运算符。这用于构建查询。然后通过 Cursor.execute() 命令将日期注入(inject)到查询中。然后,MySQLdb 会根据您的数据构建安全查询,并且不会允许恶意用户注入(inject)自己的 SQL 来代替日期字符串。

import MySQLdb

def query1(date, comp):
query = '''
select *
from table
where number {comp} 1
and date = %s
'''.format(comp=sql_comp_operator(comp))

cursor.execute(query, (date, ))
return cursor.fetchall()

def sql_comp_operator(comp):
operators = {
'lt': '<',
'lte': '<',
'gt': '>',
'gte': '>=',
}
if comp in operators:
return operators[comp]
else:
raise ValueError("Unknown comparison operator '{}'".format(comp))

query1('2013-01', 'lte')

关于python - 在 python 中传递 le 或 ge 符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16006612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com