“%s"% 格式 vs “{0}".format() vs “?"格式 [英] "%s" % format vs "{0}".format() vs "?" format

查看:47
本文介绍了“%s"% 格式 vs “{0}".format() vs “?"格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这篇 关于 SQLite 的帖子中,aaronasterling 告诉我

In this post about SQLite, aaronasterling told me that

  • cmd = "attach \"%s\" as toMerge" % "b.db" : 是错误的
  • cmd = 'attach "{0}" as toMerge'.format("b.db") :正确
  • cmd = "attach ? as toMerge";cursor.execute(cmd, ('b.db', )) : 是对的
  • 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?

推荐答案

"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")

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

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', ))

这个完全省略了字符串格式,而是使用了 SQLite 功能,所以这是正确的方法.

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

大优势:无SQL注入风险

Big advantage: no risk of SQL injection

这篇关于“%s"% 格式 vs “{0}".format() vs “?"格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆