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

标签 python

我正在尝试通过提供从这样的方法中获取的参数来格式化 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),请使用它。

关于Python 字符串格式 - 字符串替换后的百分比符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51960654/

相关文章:

python - numpy.minimum 用于复数

python - 将二维数组的前 3 个元素插入 MySql 数据库

python - 使用 StreamBlock 时如何解决 Wagtail 循环 block 依赖

python - 当python xarray模块中每个像素的范围不同时,是否可以按时间范围选择数据集

python - F2PY - 从子程序访问模块参数

python - __getattr__ 和 __getattribute__ 用于动态生成的类的类/静态属性

python - 如果变量包含的只是数字,如何知道变量是分类变量还是数值变量?

python - 使用 PyPDF2 合并两个 pdf 文件时出错

python - 为什么带有正参数的 relativedelta 返回过去的日期?

python - Siamese Network 上的损失不会减少