0

I'm relatively new into Python and I've got a question: How can I input a variable into an SQL execution?

sql = "Insert INTO links VALUES('stackoverflow')"

Obviously, 'stackoverflow' is just a string but what do I need to change if I want to insert a variable?

Thanks for your help! Melodlebron

0

1 Answer 1

-2

what you seem to be needing is a dynamically formatted string, Python has those in the form of:

 stackoverflowString = "stackoverflow"
 sql = ("Insert INTO links VALUES('%s')" % stackoverflowString)

This will replace the string stackoverflowString inside the SQL statement.

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

6 Comments

What happens if stackoverflowString is 'DROP TABLE links;-- in your case? (hint: nothing good). The query needs to be properly parametrized.
Thank you I forgot to escape the string.
The brackets around the query don't make it any safer.
Just leave parametrizing to the sql-connector you are using. cursor.execute(insert_statement, data) will work perfectly fine, no reason to homebrew these things.
Thanks it worked! You're great!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.