0

I am trying to pass a variable loc into my execute statement to get an individual slug number from my db but cant figure out how to pass it through. I have my methods set up this way because there are several different queries I will possibly perform and didnt want a bunch of repeat code.

def query(sql): 
    db = mysql.connector.connect(
        host="localhost",
        user="root",
        passwd="password!",
        database="db"
    )

    cursor = db.cursor()
    cursor.execute(sql)
    final_result = [i[0] for i in cursor.fetchall()]
    return final_result


def individual(loc):
    sql = "SELECT slug FROM auctions WHERE location = %s", loc
    return query(sql)

1 Answer 1

1

I usually do it like this

sql = """SELECT slug FROM auctions WHERE location = %(loc_name)s
    """
cursor.execute(sql, {"loc_name": loc,})

pass the value as dictionary. feels safer and tidier :)

if 'sometimes' you need all slugs and 'sometimes' you need a specific slug based on location

if loc: #check if there is loc value
    sql = """SELECT slug FROM auctions WHERE location = %(loc_name)s"""
    cursor.execute(sql, {"loc_name": loc,})
else:
    sql = """SELECT slug FROM auctions"""
    cursor.execute(sql)

that will work, but feels like there is a better writing style.. hmm..

Sign up to request clarification or add additional context in comments.

3 Comments

Sometimes I need all the slugs though so the location doesn't matter. If I execute without a location Ill get errors right?
Im just writing it based on your string.. I'll edit my answer to cover your comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.