【问题标题】:MySQL query with Python not returning all results使用 Python 的 MySQL 查询不返回所有结果
【发布时间】: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


【解决方案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()

【讨论】:

  • 不幸的是,这对我也不起作用。我得到的结果与我最初的结果相同。我已经手动测试了查询,所以我知道它肯定有效。如果查询没有参数,它就可以工作,但是一旦将它们添加进去,它只会给出单个结果。
  • 我对代码做了一点改动。 (将 .strip() 添加到 line 参数)。也许这可以解决您的问题,因为我猜想否则会包含结束字符...
  • 没问题:-)如果您认为我的回答有用,您可以投票吗?
【解决方案2】:

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

        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,我猜这将是行。

【讨论】:

  • 我在打开连接之前已经打开了输出文件。应该包括那个对不起,但我已经更新了我现在发布的代码。有些东西确实被写入了输出文件,只是不是所有的东西都在那里。至于参数太多,那只是我发布的错误。我在我的代码中正确并在这里修复了它,对此感到抱歉。
猜你喜欢
  • 2015-06-11
  • 2023-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-22
  • 2014-04-24
  • 1970-01-01
相关资源
最近更新 更多