我有mysql select命令,它根据两个select命令计算返回的行数,如下所示:
SELECT count(*)-1 as elmlen FROM invertedindextb WHERE
dewId IN
(SELECT dewId FROM invertedindextb WHERE eTypeId = ? and trm = ?)
and docId IN
(SELECT docId FROM invertedindextb WHERE eTypeId = ? and trm = ?)
我写了一个python函数,它实现了上面的select命令,如下所示:
def lenOfNode (self, cursor, eTypeId , trm):
sql = """ SELECT COUNT(*)-1 AS LEN FROM invertedindextb WHERE \
dewId IN ("SELECT dewId FROM invertedindextb WHERE eTypeId = '%d' and trm = '%s' %(eTypeId,trm)") \
and docId IN ("SELECT docId FROM invertedindextb WHERE eTypeId = '%d' and trm = '%s' %(eTypeId,trm)") """
cursor.execute(sql)
results = cursor.fetchone()
print results[0]
return results[0]
虽然函数运行(但计算错误的答案),我不确定select命令的语法在python中是否正确。
有人可以帮助我使用正确的语句
答案 0 :(得分:0)
不要在\
字符串中使用sql
,而是使用三重引号启动它,因此所有新行都已确定。
您将%
运算符的参数放入字符串中,将它们转换为文字文本。尝试在执行之前打印查询,例如
def lenOfNode (self, cursor, eTypeId , trm):
sql = """ SELECT COUNT(*)-1 AS LEN FROM invertedindextb WHERE \
dewId IN ("SELECT dewId FROM invertedindextb WHERE eTypeId = '%d' and trm = '%s' %(eTypeId,trm)") \
and docId IN ("SELECT docId FROM invertedindextb WHERE eTypeId = '%d' and trm = '%s' %(eTypeId,trm)") """
print "My real sql query was:\n", sql
cursor.execute(sql)
results = cursor.fetchone()
print results[0]
return results[0]
你的错误是"aaa %d" % (10,)
字符串(应该给"aaa 10"
)变成'''"aaa %d" % (10,)'''
(并且会给'"aaa %d" % (10,)'
),这不是你想要的。对我来说,了解这些事情的最好方法是使用%ed magick命令在IPython控制台中尝试我所有可疑的部分代码。
在sql查询中使用%s
会在代码中引入直接漏洞--sql注入。
答案 1 :(得分:0)
我忘了在第一个select命令和where子句中的第二个命令之间添加“and”运算符,所以在def运行时添加和运算符如下,并返回正确的结果:
sql = """ SELECT (COUNT(*)-1) AS LEN FROM invertedindextb WHERE
(dewId IN (SELECT dewId FROM invertedindextb WHERE eTypeId = '%d' and trm = '%s') and
docId IN (SELECT docId FROM invertedindextb WHERE eTypeId = '%d' and trm = '%s')) """ %(eTypeId,trm,eTypeId,trm)