0

I have started a small project yesterday in python and finally managed to make a database selection function that works, but I was wondering if anybody could tell me if the way I wrote it is good or could eventually end up in multiple problems.

The idea was to make a function that I could call to request/update a table where I would store players data for a small online game I want to create via Python, Pygame and MySQL.Connector-Python

So, here is the function code (I have tried to keep it as clean as possible and as intuitive as I could with my current knowledge of Python which is limited currently as I just picked it back up this week.)

The part I am not sure is the select_statement variable where I do not know for sure if the way I used concatenation is okay or if there is a way as simple and efficient.

def db_select(selection, table):
    dbc = db_connect()

    if dbc:
        print("The SQL connection was successful.")
    else:
        print("The SQL connection could not be established.")

    cur = dbc.cursor()

    select_statement = "SELECT * FROM " + table + " WHERE id = %(id)s"

    cur.execute(select_statement, {'id': selection})

    print(cur.fetchone()[1])

    dbc.close()
    print("The SQL connection was closed successfully.")
2

1 Answer 1

0

Python has the .format()syntax just for these kinds of situations - handling a dynamic value (such as table being inserted into a string (including SQL queries).

query = "SELECT * FROM {} WHERE id = %(id)s".format(table)

It's cleaner and more reliable in my daily use than the prior approaches such as yours.

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

2 Comments

Thanks for the quick answer :), I tried to find some documentation on that, but found nothing for the past three hours. I will add the accepted answer as soon as the four minutes delay passes. Thank you again :)
@Avarthar here is a decent overview programiz.com/python-programming/methods/string/format, it's pretty simple unless you try to do something seriously complex. For example, expanding on your original query, is super simple: SELECT * FROM {} WHERE id = {}".format(table, int(id))

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.