2

I'll admit it. I've been doing this for literally decades:

sql = 'select * from whatever where key = "%s"' % ('thing')
cursor.execute(sql)

One big reason is that

print(sql)

tells me something useful. Whereas this:

sql = 'select * from whatever where key = :key'
params = {'key': 'thing'}
cursor.execute(sql, params)

has no way to do that. Or does it? Note that this isn't as easy as doing this:

print(replace_with_dict_values(sql, params))

(replace_with_dict_values isn't real, but could easily be made.) Why not? Because in the above example, I would get this printed out:

select * from whatever where key = thing

which is missing the quoting. I want to know what the actual sql would be so I can cut and paste it into a sql editor and run the query myself while debugging. ("actual SQL" basically means "what the equivalent sql would be" and can probably be found by asking the cursor to preform the bindings and return the string. but how?)

18
  • execute executes what you tell it to execute. In this case, you created a query string through string formatting which exposes you to SQL injection. Use parameterized queries instead. NO amount of quoting can avoid the injection and conversion errors caused by string concatenations. Commented Oct 23, 2020 at 12:51
  • 1
    I think the answer may depend on which database you are using. For example, with postgres, you can use mogrify. Commented Oct 23, 2020 at 12:51
  • This might not be quite that straightforward since with prepared statements and placeholders there may not exist a concrete SQL statement with the constant values "quoted in" at any point in time. Commented Oct 23, 2020 at 12:51
  • @PanagiotisKanavos Read the question again... OP is using parameterized queries, and that's part of their issue. Commented Oct 23, 2020 at 12:52
  • 2
    @PanagiotisKanavos "When using parametrized queries, is there a way to get a concrete query I could e.g. paste into an external SQL editor?". Commented Oct 23, 2020 at 12:53

0

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.