Will using F-strings to request data cause SQL injections?

Question:

I’m unfamiliar with how injection attacks work. Will using f-strings in .execute() make me vulnerable to injection, if I only request data (not update/insert)?

Similarly, let’s say I’m trying to edit a column. How can I put in my own variables through .execute() without an f-string?

i.e.

new_date = '30/10/2022'

my_database.execute(f'UPDATE people SET birthday={new_date} WHERE name="Odin"')

What would be the best way to update the data?

Also, how do I tell if a database has been corrupted?

Edit: I should add my own understanding of ‘vulnerability.’ The user could input their own SQL commands into new_date so that the execute will input a different command.

Asked By: Titan31 Hunter29

||

Answers:

Yes, it will leave you vulnerable, only if new_date can be changed by users. For example, let’s say new_date is set to 30/10/2022; DROP DATABASE users -- by a user. The f-string will then resolve to

UPDATE people SET birthday=30/10/2022; DROP DATABASE users -- WHERE name="Odin"

If this query is sent to your database, then it will delete a database named users.

To make user input safe to be sent to a database, you must sanitize it. To sanitize your database input, see this web page. For example, code is safe:

my_database.execute('UPDATE people SET birthday=%s WHERE name="Odin"', (new_date,))

If new_date is constant and cannot be changed in any way by the user, it is theoretically safe. However, always err on the side of caution. Personally, I choose to sanitize all input and not risk it.

Answered By: Michael M.