1

I have 3 arguments date, Name and country, this code allows to pass my optionals arguments for my SQL query, for example :

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)

My SQL qyery :

'SELECT * FROM TABLE WHERE date=%s and name=%s'

I want call my script like :

script.py --date=var1 --name=var3

Now, if I have a date range, how can I add this argument with the close between in my SQL to have a query like :

'SELECT * FROM TABLE WHERE date between %s and %s and name=%s'

How CAN I DO it please

Flora8832
  • 57
  • 5

1 Answers1

0

I think this is what you're looking for:

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)

What I've done here:

  • Specify the number of --date arguments using nargs=2
  • Used vars to get a dict instead of args.__dict__
  • Added a special check for date
  • Used a for loop to add other optional arguments

You can see some example outputs below:

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
Alex
  • 6,610
  • 3
  • 20
  • 38
  • That returns `SELECT * FROM TABLE WHERE date BETWEEN 2020-03-01 AND 2020-03-02 and country=USA` – Alex Dec 11 '20 at 09:31