“%s” % format vs “{0}”.format() vs “?” format

后端 未结 3 703
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 16:42

In this post about SQLite, aaronasterling told me that

  • cmd = \"attach \\\"%s\\\" as toMerge\" % \"b.db\" : is wrong
  • cmd = \'attach
3条回答
  •  旧时难觅i
    2020-12-08 17:12

    "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

提交回复
热议问题