1

I have the below code in which I want my MySQL query select those values in the 'name' column that are identical to the value in 'filenames' python list. I keep get an empty () as for the result. Can anyone help me with this?

import MySQLdb
import fnmatch
import os
import pprint

connect = MySQLdb.connect(host = "123.5.4.4", port=3366, user = "me", passwd="*********", db="data2")

filenames=[]
maindict = {}  

for root, dirnames, filenames in os.walk('d:/data1'):  
    for filename in fnmatch.filter(filenames, '*.txt'):   
       filenames.append(filename)

with connect:            
    cur= connect.cursor()            
    cur.execute("SELECT version,name FROM data2.files WHERE name IN ('filenames'.join('')" )
    result = cur.fetchall()

pprint.pprint(result)  
st0ne
  • 4,165
  • 2
  • 23
  • 24
UserYmY
  • 8,034
  • 17
  • 57
  • 71

2 Answers2

1

replace:

cur.execute("SELECT version,name FROM data2.files WHERE name IN ('filenames'.join('')" )

with:

cur.execute("SELECT version,name FROM data2.files WHERE name IN ('%s')" % "','".join(filenames) )

in python shell:

>>> filenames=['file1', 'file2']
>>> query = "SELECT version,name FROM data2.files WHERE name IN ('%s')" % "','".join(filenames)
>>> print query
SELECT version,name FROM data2.files WHERE name IN ('file1','file2')
>>>
st0ne
  • 4,165
  • 2
  • 23
  • 24
1

You should use

cur.execute(
    "SELECT version,name FROM data2.files WHERE name IN (" +
    ",".join(("%s",) * len(filenames)) + 
    ")",
    tuple(filenames)
)

This creates a SQL string of the form

WHERE name IN (%s,%s,%s,%s)

with as many %ss you need and makes the MySQL module replace them with the filenames data, taking care of quoting as needed.

glglgl
  • 89,107
  • 13
  • 149
  • 217