"%s" % format vs "{0}".format() vs "?" format
Asked Answered
L

3

16

In this post about SQLite, aaronasterling told me that

  • cmd = "attach \"%s\" as toMerge" % "b.db" : is wrong
  • cmd = 'attach "{0}" as toMerge'.format("b.db") : is correct
  • cmd = "attach ? as toMerge"; cursor.execute(cmd, ('b.db', )) : is right thing

But, I've thought the first and second are the same. What are the differences between those three?

Lorenelorens answered 11/9, 2010 at 17:45 Comment(0)
N
20
"attach \"%s\" as toMerge" % "b.db"

You should use ' instead of ", so you don't have to escape.

You used the old formatting strings that are deprecated.

'attach "{0}" as toMerge'.format("b.db")

This uses the new format string feature from newer Python versions that should be used instead of the old one if possible.

"attach ? as toMerge"; cursor.execute(cmd, ('b.db', ))

This one omits string formatting completely and uses a SQLite feature instead, so this is the right way to do it.

Big advantage: no risk of SQL injection

Noachian answered 11/9, 2010 at 17:56 Comment(0)
V
6

The first and second produce the same result, but the second method is prefered for formatting strings in newer versions of Python.

However the third is the better approach here because it uses parameters instead of manipulating strings. This is both faster and safer.

Vial answered 11/9, 2010 at 17:51 Comment(1)
the second method, by being preferred in newer versions of python is, by extension, preferred for new code in all versions of python that support it. It's a simple matter of forward compatibilityCoquille
M
3

Because it is not being escaped. If you replaced the b.db with user input, it would leave you vulnerable to SQL injection.

Melt answered 11/9, 2010 at 17:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.