遇到一个挺诡异的问题
一直都是用execute加%s的方式执行SQL,因为说这样可以拦截SQL注入.
但是今天,相同的SQL在数据库连接工具能正常执行,放进了Python没有任何报错返回空元组.

部分代码示意

def selectInformation(self,colume,key):
    sql = "select * from `host` where %s = %s order by `time` desc limit 1;"
    self.cursor.execute(sql,[colume,key])
    print(self.cursor.fetchall())

SQL是根据提供的列和列值进行替换查询指定的列
数据库是有数据的,相同的语句替换掉%s就可以正常执行.
但是上段代码执行报错了,翻阅部分源码说支持三种传参,列表.元组,或者字典.

换成字典再次试了下

def selectInformation(self,colume,key):
    sql = "select * from `host` where %(colume)s = %(key)s order by `time` desc limit 1;"
    self.cursor.execute(sql,{'colume':colume,'key':key})
    print(self.cursor.fetchall())

但是还是不行.

群里某位大佬让我格式化字符串试了下,成了…

解决方式:改为format或其他字符串格式化方式

def selectInformation(self,colume,key):
    sql = "select * from `host` where {} = '{}' order by `time` desc limit 1;".format(colume,key)
    # try:
    self.cursor.execute(sql)
    # except:
    #     return {'error':'query error,please check args'}
    print(self.cursor.fetchall())
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐