In this post about SQLite, aaronasterling told me that
cmd = "attach \"%s\" as toMerge" % "b.db"
: is wrongcmd = 'attach "{0}" as toMerge'.format("b.db")
: is correctcmd = "attach ? as toMerge"; cursor.execute(cmd, ('b.db', ))
: is right thingBut, I've thought the first and second are the same. What are the differences between those three?
%s acts as a placeholder for the real value. You place the real value after the % operator. This method is often referred to as the "older" way because Python 3 introduced str. format() and formatted string literals (f-strings).
The difference between %s and %r is that %s uses the str function and %r uses the repr function. You can read about the differences between str and repr in this answer, but for built-in types, the biggest difference in practice is that repr for strings includes quotes and all special characters are escaped.
The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value.
%s acts a placeholder for a string while %d acts as a placeholder for a number.
"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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With