“%s” % format 与“{0}”。format() 与“?”格式
在这篇关于 SQLite 的帖子中, aaronasterling 告诉我
cmd = "attach \"%s\" as toMerge" % "b.db"
:错误cmd = 'attach "{0}" as toMerge'.format ("b.db")
:正确cmd = "attach ? as toMerge"; cursor.execute(cmd, ('b.db', ))
:是对的
但是,我认为第一个和第二个是相同的。这三者有什么区别?
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 thing
But, I've thought the first and second are the same. What are the differences between those three?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该使用
'
而不是"
,这样您就不必转义。您使用了已弃用的旧格式字符串。
这使用了较新版本的新格式字符串功能如果可能的话,应该使用 Python 版本来代替旧版本,
这个版本完全省略了字符串格式并使用 SQLite 功能,因此这是正确的方法,
最大的优点是:没有 SQL 注入的风险。
You should use
'
instead of"
, so you don't have to escape.You used the old formatting strings that are deprecated.
This uses the new format string feature from newer Python versions that should be used instead of the old one if possible.
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
第一个和第二个产生相同的结果,但第二种方法更适合在较新版本的 Python 中格式化字符串。
然而,第三种方法是更好的方法,因为它使用参数而不是操作字符串。这既更快又更安全。
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.
因为它没有被逃脱。如果您用用户输入替换 b.db,那么您很容易受到 SQL 注入的攻击。
Because it is not being escaped. If you replaced the b.db with user input, it would leave you vulnerable to SQL injection.