在 cursor.execute mysql 查询中传递元素列表
pass list of elements inside cursor.execute mysql query
我有一个包含多个元素的列表:
l=['asia','america','africa','australia'].
我有 mysql table 并且我只想计算列的所有行中单词的出现次数,例如,如果 asia
是我要检查的单词计数然后我使用:
cursor.execute("select count(*)from table_text where round(match(text) against('asia'),5)")
cursor.fetchall()
我被算作 48
。我如何将所有列表元素作为参数传递给 cursor.execute
并同时计算所有单词数?
我做了一些事情:-
for i in l:
cursor.execute("select count(*)from table_text where round(match(text) against('"i"'),5)")
cursor.fetchall()
出现错误!!!
我不确定您要对查询做什么。我看到了一些错误:
select count(*)from table_text where round(match(text) against('"i"'),5)
首先在count和from之间加一个space
其次条件'match(text) against('"i"')'是有道理的,但是轮函数的目的是什么?
最后,有了count这样的聚合函数,最后还需要一个groupby
我认为你可以在你的条件中使用 spaces 来匹配其中一个词。类似于:
conditions = '"' + ' '.join(l) + '"'
# conditions = '"asia america africa australia"'
query = 'SELECT count(*) FROM table_text WHERE MATCH(text) AGAINST(' + conditions + ' IN BOOLEAN MODE)'
还要注意引号和双引号。 l 的元素有单引号,而您的查询使用双引号。
只需对字符串使用 +
运算符。所以,你可以这样做:-
list_new=[]
for words in l:
cursor.execute("select count(*)from table_text where round(match(text) against('"+words+"'),5)")
tagg=cursor.fetchall()
for i in tagg[0]:
list_new.append(i)
print (list_new) #Gives you list of counts of all elements
希望对您有所帮助!!!!
我有一个包含多个元素的列表:
l=['asia','america','africa','australia'].
我有 mysql table 并且我只想计算列的所有行中单词的出现次数,例如,如果 asia
是我要检查的单词计数然后我使用:
cursor.execute("select count(*)from table_text where round(match(text) against('asia'),5)")
cursor.fetchall()
我被算作 48
。我如何将所有列表元素作为参数传递给 cursor.execute
并同时计算所有单词数?
我做了一些事情:-
for i in l:
cursor.execute("select count(*)from table_text where round(match(text) against('"i"'),5)")
cursor.fetchall()
出现错误!!!
我不确定您要对查询做什么。我看到了一些错误:
select count(*)from table_text where round(match(text) against('"i"'),5)
首先在count和from之间加一个space
其次条件'match(text) against('"i"')'是有道理的,但是轮函数的目的是什么?
最后,有了count这样的聚合函数,最后还需要一个groupby
我认为你可以在你的条件中使用 spaces 来匹配其中一个词。类似于:
conditions = '"' + ' '.join(l) + '"'
# conditions = '"asia america africa australia"'
query = 'SELECT count(*) FROM table_text WHERE MATCH(text) AGAINST(' + conditions + ' IN BOOLEAN MODE)'
还要注意引号和双引号。 l 的元素有单引号,而您的查询使用双引号。
只需对字符串使用 +
运算符。所以,你可以这样做:-
list_new=[]
for words in l:
cursor.execute("select count(*)from table_text where round(match(text) against('"+words+"'),5)")
tagg=cursor.fetchall()
for i in tagg[0]:
list_new.append(i)
print (list_new) #Gives you list of counts of all elements
希望对您有所帮助!!!!