Search code examples
pythonmysqlpython-3.xpymysql

pass list of elements inside cursor.execute mysql query


I have a list of multiple elements as :

l=['asia','america','africa','australia']. 

I have mysql table and all I want to count a occurance of word within all rows of column so for example if asia is a word of which I want to check count then I used:

cursor.execute("select count(*)from table_text where round(match(text) against('asia'),5)") cursor.fetchall()

and I got count as 48. How I can pass all list elements as parameter inside cursor.execute and get all words count simultaneously? I did something as:-

for i in l:
    cursor.execute("select count(*)from table_text where round(match(text) against('"i"'),5)")
    cursor.fetchall()

That gives an error!!!


Solution

  • Just use + operator for string. So, you can do something like:-

    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
    

    Hope it helps!!!!