Python字符串格式化-字符串替换后的百分比符号

sys*_*ser 3 python

我试图通过提供从这样的方法中获取的参数来格式化 python 中的 SQL 查询

query = "select * from employees where employee_name like '%s%'" % (name)
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,出现以下错误(python 2.6)

ValueError: unsupported format character ''' (0x27) at index 886
Run Code Online (Sandbox Code Playgroud)

我也在命令行中尝试了这个来找出问题

>>> print "hello '%s'" % ('world')
hello 'world'
>>> print "hello '%s\%'" % ('world')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> print "hello '%s%'" % ('world')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> 
Run Code Online (Sandbox Code Playgroud)

当我没有立即在单引号内添加 % 时,%s 会起作用,但当我在单引号后添加 % 时,即使进行转义,%s 也会中断。有没有补救措施,如果没有这个,我无法在 SQL 查询中替换变量。

Mic*_*ler 5

SQL注入漏洞就是这样诞生的。SQL 注入会让入侵者读取私有数据,甚至可能修改数据。永远不要将原始字符串传递到 SQL 查询中,除非您确保它没有特殊字符,例如'%\。实际上,最好使用经过充分测试的函数来为您完成此操作。

你可能会认为:

query = "select * from employees where employee_name like '%s%%'" % (name)
# (two `%%` at the end)
Run Code Online (Sandbox Code Playgroud)

解决了你的问题,但如果以某种方式name == "%' or '' like '" (或类似的东西),那么查询突然变成:

"select * from employees where employee_name like '%' or '' like '%'"
Run Code Online (Sandbox Code Playgroud)

这将匹配所有员工。更糟糕的是,name = ''对你来说甚至是一场噩梦。like首先,我认为在此类查询中使用并不是一个好主意。

有关安全格式化的一些信息,您可以阅读sql-injection标签下的堆栈溢出问题,例如Protecting against SQLinjection in python。每个数据库系统都提供自己的存储过程接口,请使用它。