“%s” % format 与“{0}”。format() 与“?”格式

发布于 2024-09-19 03:57:37 字数 442 浏览 3 评论 0原文

在这篇关于 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 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

粉红×色少女 2024-09-26 03:57:37
"attach \"%s\" as toMerge" % "b.db"

您应该使用 ' 而不是 ",这样您就不必转义。

您使用了已弃用的旧格式字符串。

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

这使用了较新版本的新格式字符串功能如果可能的话,应该使用 Python 版本来代替旧版本,

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

这个版本完全省略了字符串格式并使用 SQLite 功能,因此这是正确的方法,

最大的优点是:没有 SQL 注入的风险。

"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

凉城已无爱 2024-09-26 03:57:37

第一个和第二个产生相同的结果,但第二种方法更适合在较新版本的 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.

牵强ㄟ 2024-09-26 03:57:37

因为它没有被逃脱。如果您用用户输入替换 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文