1

我有下面的代码,我希望我的 MySQL 查询在“名称”列中选择与“文件名”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)  
4

2 回答 2

1

你应该使用

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数据替换它们,并根据需要处理引用。

于 2013-04-03T10:01:26.067 回答
0

代替:

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

和:

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

在 python 外壳中:

>>> 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')
>>>
于 2013-04-03T09:43:13.207 回答