0

I need to create a dynamic query based on two string parameters:

description = "This is the description"
comment = "This is the comment"
query = "insert into case(desc, comm) value(description, comment)"

Note: there might be single quote and double quotes in both description and comment.

How do I use formatted %s to generate the query string?

Thank you very much.

UPDATE:

Thanks to Green Cloak Guy (his/her answer has minors to be corrected), the right query is:

query = f"insert into case(description, comment) value(\'{description}\', \'{comment}\')"

1 Answer 1

1

Use an f-string.

query = f"insert into case({description}, {comment}) value({description}, {comment})"

Don't use any type of string formatting to do actual database queries - that leads to you having a SQL Injection problem. Use a database library instead, that properly sanitizes the data.

But if all you need to do is parse some variables into a string, this is more flexible than the % formatting that other languages tend to use (and that's technically still available in python via "some_string %s %s %s" % (str1, str2, str3)")

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

1 Comment

Thank you, in the value part, both should be single quoted,

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.