-1

I have 2 short python scripts with similar functions. How can I combine the script into one and to call one variable when needed.

cee
  • 3
  • 2
  • When you have identical code repeating with only one value changing - that calls for a function. Take [The Python Tutorial](https://docs.python.org/3/tutorial/index.html) to learn about how these work in general and specifically in Python – Tomerikoo Jan 11 '22 at 15:32

1 Answers1

0

Make a method with the common code, then call with the specific value for each

Also don't use string formatting to pass values to query, use placeholders and let the SQL engine handle it (?s for mysql), see How to use variables in SQL statement in Python?

def method(initial_query):
    cur = con.cursor()
    try:
        cur.execute(initial_query)
        release_rec = cur.fetchall()
        for row in release_rec:
            query = "select count (*) from food.veggie.celery and release_id=%s"
            cur.execute(query, (row[0],))
            ...

method("select release_id,release_codes:transfer_date from food.fruit.apple where release_codes:transfer_date between '2020-11-01' and '2020-11-30'")

method("select release_id, release_codes:transfer_date from food.fruit.apple order by release_id")
azro
  • 53,056
  • 7
  • 34
  • 70
  • Thank you. What does the initial_query mean? What do I put in it? – cee Jan 11 '22 at 15:23
  • @cheezy967 That is a parameter of the method, Strange that you deal with such level of code, sql and all that, and you don't even know about method and their parameter, I suggest you quickly go back to basic tutorials – azro Jan 11 '22 at 15:24