db.query中的变量使用不当

时间:2013-03-25 21:23:35

标签: database web.py

您好我正在尝试开发一个使用webpy的博客,

def getThread(self,num):
        myvar = dict(numero=num)
        print myvar
        que = self.datab.select('contenidos',vars=myvar,what='contentTitle,content,update',where="category LIKE %%s%" %numero)

        return que

我已经使用了你在这个网站上回答的一些技巧,但我只得到了

  在/ /   全局名称'numero'未定义

     

getThread中的Python C:\ xampp \ htdocs \ webpy \ functions.py,第42行   Web GET http://:8080/   ...

我正在尝试选择一些分类的帖子, 有一个类别名称和ID的表格 在内容表中有一个列,它将采用一个字符串,它将被格式化为“1,2,3,5” 那么我认为我可以用LIKE语句选择正确的条目和%some something%magic。但我有这个问题。

我从构建网络的.py文件中调用代码,import语句正常工作 getThread在这个类中被定义:

class categoria(object):
    def __init__(self,datab,nombre):

        self.nombre = nombre
        self.datab = datab
        self.n = str(self.getCat()) #making the integer to be a string 
        self.thread = self.getThread(self.n)
        return self.thread

    def getCat(self):
        '''
        returns the id of the categorie (integer)
        '''
        return self.datab.select('categorias',what='catId', where='catName = %r' %(self.nombre), limit=1)

1 个答案:

答案 0 :(得分:1)

请检查db.selecthttp://webpy.org/cookbook/select)的正确语法,不应使用“%”格式化查询,因为它会使代码容易受到sql注入攻击。相反,将vars放入dict并在查询中使用$引用它们。

myvars = dict(category=1)
db.select('contenidos', what='contentTitle,content,`update`', where="category LIKE '%'+$category+'%'", vars=myvars)

将生成此查询:

SELECT contentTitle,content,`update` FROM contenidos WHERE category LIKE '%'+1+'%'

请注意,我反引用update,因为它是SQL中的保留字。