SQL字符串替换错误没有足够的参数用于格式字符串 [英] SQL string substitution error not enough arguments for format string

查看:70
本文介绍了SQL字符串替换错误没有足够的参数用于格式字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试返回一个查询,以获取所有以字符串开头的记录,例如varibale,我有
,所以我这样做了:

I'm trying to return a query to get all records that begin with string like a varibale i have so i do so :

"""select name from pos_order where name like '%s'||'%' order by id DESC limit 1"""%(darsh[0])

其中 darsh 类似于'mostafa /'

但它一直告诉我格式字符串的参数不足

我不知道为什么。

推荐答案

Python尝试替换两个'% sql中的'个字符。但是只能使用一个值-darsh [0]。因此,错误消息将尝试填写两个值,但您只给了它一个。

Python tries to substitute both '%' characters in your sql. But it only has one value - darsh[0] - to use. Hence the error message, it is trying to fill in two values, but you've only given it one.

为证明这一点,请逃避第二个%%,语句

To prove this, escape the second %%, making your statement

从pos_order中选择名称,其中名称类似'%s'||'%%',按ID DESC限制1%(darsh [0 ])

"""select name from pos_order where name like '%s'||'%%' order by id DESC limit 1"""%(darsh[0])

但是 不要这样做-这会使您容易受到SQL注入的攻击。例如,如果您的数据库中有一个名为DO_BAD_THING的函数,则恶意用户可能会使用精心设计的输入字符串来使该函数执行。

but Don't do this - it makes you vulnerable to SQL Injection. For example, if you had a function in your database called DO_BAD_THING a malicious user could make that function execute using a carefully crafted input string.

正确的答案是使用绑定变量,请参见以下问题:

The correct answer is to use a bind variable, see this question :

有关postgresql绑定变量的问题

例如这个怎么做。

为强调起见-不要将字符串连接用于SQL的任何终端用户可以操纵字符串的任何地方。

For emphasis - don't use string concatenation for SQL for anything where an end user can ever manipulate the string.

这篇关于SQL字符串替换错误没有足够的参数用于格式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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