【发布时间】:2013-07-05 13:51:14
【问题描述】:
我已经编写了一些 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()关闭了文件?如果没有,可能数据在输出缓冲区中丢失了。 -
备案:“args = (line)”应该是“args = (line,)”,但请参阅 joente 的答案以获得真正的修复。
标签: python mysql mysql-connector