我已经编写了一些python代码来连接到MySQL数据库,打开一个文本文件,并对文本文件中的每个条目执行查询并将结果写入输出文件。而不是将每个查询的结果写入输出文件,但只写入一个结果。如果我使用的查询没有参数,它一切正常。只有当我尝试添加参数时才会出现此问题。使用Python进行MySQL查询不返回所有结果
我对Python很新,所以我可能会犯一个愚蠢的错误,但我还没有能够遇到任何有帮助的东西,所以任何援助将不胜感激。
我的代码是:
output = open("results.txt", "w+")
cnx= mysql.connector.connect(**config)
cursor = cnx.cursor()
with open("input.txt") as i:
for line in i:
# Construct query to get type
query = ("select type from table1, table2 "
"where table1.name = %s and table1.id = table2.id")
# Query arguments
args = (line)
cursor.execute(query, args) # Execute query
for entry in cursor:
output.write(str(entry) + "\n")
cursor.close()
cnx.close()
你使用关闭文件'output.close ()'?否则,可能数据在输出缓冲区中丢失。 – dnet
记录:“args =(line)”应该是“args =(line,)”,但请参阅joente的答案以获得真正的修复。 – geertjanvdk