pro*_*eek 15 python string-formatting pysqlite
在这篇关于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', )) :是对的但是,我认为第一和第二是相同的.这三者有什么不同?
leo*_*luk 20
"attach \"%s\" as toMerge" % "b.db"
Run Code Online (Sandbox Code Playgroud)
你应该使用'而不是",所以你不必逃避.
您使用了不推荐使用的旧格式字符串.
'attach "{0}" as toMerge'.format("b.db")
Run Code Online (Sandbox Code Playgroud)
这使用了较新Python版本的新格式字符串功能,如果可能,应使用旧版本而不是旧版本.
"attach ? as toMerge"; cursor.execute(cmd, ('b.db', ))
Run Code Online (Sandbox Code Playgroud)
这其中省略字符串完全格式化,并使用一个SQLite的功能,而不是,所以这是做正确的方式.
大优势:没有SQL注入的风险
第一和第二产生相同的结果,但第二种方法是首选为在Python的较新版本的格式的字符串.
然而,第三种是更好的方法,因为它使用参数而不是操纵字符串.这既快又安全.