Skip to main content
 首页 » 编程设计

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

2025年05月04日17EasonJim

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

query = "select * from employees where employee_name like '%s%'" % (name) 

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

ValueError: unsupported format character ''' (0x27) at index 886 

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

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

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

请您参考如下方法:

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

你会认为:

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

解决了你的问题,但是如果不知何故 name == "%' or '' like '" (或类似的东西),那么查询突然变成:

"select * from employees where employee_name like '%' or '' like '%'" 

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

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