使用Python的MySQL查询不返回所有结果

时间:2013-07-08 09:23:52

标签: python mysql mysql-connector

我编写了一些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()

2 个答案:

答案 0 :(得分:1)

我不确定您使用的查询,但我认为如果您的查询有效,这应该接近您想要的内容:

output = open('myoutputfile.txt', 'w')
cnx = mysql.connector.connect(**config)  
cursor = cnx.cursor()                       

# Construct query to get type, there's no need to include this in the loop
query = ("""SELECT type FROM table1, table2 
    WHERE table1.name = %s AND table1.id = table2.id""")

with open("input.txt") as f:
    for line in f:                                  

        # Query arguments
        args = (line.strip(), ) # added .strip()

        cursor.execute(query, args)       # Exec query

        entries = cursor.fetchall()
        for entry in entries:                
            output.write(str(entry[0]) + "\n") 

cnx.close()
output.close()

答案 1 :(得分:0)

您没有打开输出文件进行编写,至少不是在您发布的代码段中。

        for entry in cursor:  
            ## what output? when and how was it opened?            
            output.write(str(entry) + "\n")

你早先用“w”(代表写入)模式打开了“output.txt”吗?在此代码中,您只在第4行打开“input.txt”文件。如果要在追加模式下写入“input.txt”文件,则代码必须为:

i.write(str(entry) + "\n")

(并且必须以追加或写入模式打开文件)。同样在查询参数中,您不需要传递四行。在您的查询中,您只提供一个参数(table1.name =%s),您只需要将参数传递给此%s,我猜这将是行。

相关问题