在下面的代码中,我希望MySQL查询在“name”列中选择与“filenames”python列表中的值相同的值。结果我总是得到一个空的。有人能帮我吗?
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)
最佳答案
你应该用
cur.execute(
"SELECT version,name FROM data2.files WHERE name IN (" +
",".join(("%s",) * len(filenames)) +
")",
tuple(filenames)
)
这将创建表单的SQL字符串
WHERE name IN (%s,%s,%s,%s)
您需要的
%s
s越多,MySQL模块就会用filenames
数据替换它们,并根据需要进行引用。关于mysql - 如何用“WHERE”解决MySQL查询中的python列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15783712/