如何使用 argparse Python 在 SQL 查询中传递日期范围参数
Posted
技术标签:
【中文标题】如何使用 argparse Python 在 SQL 查询中传递日期范围参数【英文标题】:How to pass date range argument in SQL query with argparse Python 【发布时间】:2021-03-21 18:09:23 【问题描述】:我有 3 个参数日期、名称和国家,此代码允许为我的 SQL 查询传递我的可选参数,例如:
import argparse
parser = argparse.ArgumentParser()
# provide a clear definition of possible arguments
parser.add_argument('--date', type=str, required=False, default=None)
parser.add_argument('--Name', type=str, required=False, default=None)
parser.add_argument('--country', type=str, required=False, default=None)
# get arguments passed in
args = parser.parse_args()
args = args.__dict__
# form statement based on arguments that were given
columns = ' and '.join([x+'=%s' for x in args if args[x]]) #check that args[x] is not None
vars = tuple([args[x] for x in args if args[x]])
statement = "SELECT * FROM TABLE WHERE "+columns
cursor.execute(statement, vars)
我的 SQL 查询:
'SELECT * FROM TABLE WHERE date=%s and name=%s'
我想像这样调用我的脚本:
script.py --date=var1 --name=var3
现在,如果我有一个日期范围,我如何在我的 SQL 中添加这个带有关闭 between
的参数来进行如下查询:
'SELECT * FROM TABLE WHERE date between %s and %s and name=%s'
请问我该怎么做
【问题讨论】:
【参考方案1】:我想这就是你要找的东西:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--date", nargs=2)
parser.add_argument("--name")
parser.add_argument("--country")
# Use `vars` to get a dict of arguments
args = vars(parser.parse_args())
# Only keep arguments that aren't `None`
args = k: v for k, v in args.items() if v is not None
# Base select statement
statement = "SELECT * FROM TABLE"
# This list will hold all the extra conditionals
operators = []
if "date" in args:
# Specifically parse the dates and then delete it from args
operators.append("date BETWEEN AND ".format(*args["date"]))
del args["date"]
# For the remaining args add them to operators
for k, v in args.items():
operators.append("=".format(k, v))
if operators:
# If there are extra operators add them to the base statement
statement = statement + " WHERE " + " and ".join(operators)
print(statement)
我在这里做了什么:
使用nargs=2
指定--date
参数的数量
使用vars
代替args.__dict__
获取字典
为date
添加了特殊检查
使用 for 循环添加其他可选参数
您可以在下面看到一些示例输出:
python3 script.py --date 2020-08-01 2020-12-25 --name alex --country Canada
SELECT * FROM TABLE WHERE date BETWEEN 2020-08-01 AND 2020-12-25 and name=alex and country=Canada
python3 script.py --date 2020-08-01 2020-12-25 --name alex
SELECT * FROM TABLE WHERE date BETWEEN 2020-08-01 AND 2020-12-25 and name=alex
python3 script.py --name alex
SELECT * FROM TABLE WHERE name=alex
python3 script.py
SELECT * FROM TABLE
【讨论】:
返回SELECT * FROM TABLE WHERE date BETWEEN 2020-03-01 AND 2020-03-02 and country=USA
以上是关于如何使用 argparse Python 在 SQL 查询中传递日期范围参数的主要内容,如果未能解决你的问题,请参考以下文章
python sum_sq_err(ys_real,ys_predicted)
Python爬虫:逆向分析酷我音乐请求参数(支持SQ超品音质)