【问题标题】:Python MySQL connector fails to return all results from SELECT queryPython MySQL 连接器无法从 SELECT 查询返回所有结果
【发布时间】:2015-03-31 23:51:56
【问题描述】:

我有这个使用 mysql-connector-python 执行的查询。代码是:

try:
    conn = mycon.connect(user=****,password=****,host=****,database=****,autocommit=True)
except mycon.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Authentication error - incorrect username and/or password.")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist.")
    else:
        print(err)
cursor = conn.cursor()
no_of_results = cursor.execute("SELECT * FROM name_table\nLIMIT 0, 1000\n")
row = cursor.fetchone()
print(row)
while row is not None:
    row = cursor.fetchone()
    print(row)
cursor.close()
conn.close()

这会返回:

(1, 'Mains', 'Mains electrical circuit.')
(2, 'Solar', 'Solar panels.')
(3, 'AirCon', 'Air conditioner.')
(4, 'Oven', 'Oven.')
(5, 'Power1', 'General power circuit 1.')
(6, 'Power2', 'General power circuit 2.')
(7, 'Lights1', 'Lights circuit 1.')
(8, 'Lights2', 'Lights circuit 2.')
None

但是,如果我通过 MySQL 工作台运行完全相同的查询,返回的结果是:

我不知道为什么这两个查询返回不同的结果。我还使用下面的wireshark查看了网络流量信息,但我没有明确的理由为什么会这样。

MySQL Workbench

Python Connector

【问题讨论】:

    标签: python mysql sql connector mysql-connector-python


    【解决方案1】:

    您必须先打印该行才能获取下一行,如下所示:

    while row is not None:
        print(row)
        row = cursor.fetchone()
    

    【讨论】:

    • 不,不是这样 - 请注意最后打印“无”。其次,如果你查看wireshark的日志,你会发现从服务器返回的数据不包括最后的结果。
    • 你有没有发现这个问题的根本原因是什么?我遇到了相反的问题...... Python 中的相同查询返回的结果比 Workbench 的结果多一个!
    猜你喜欢
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    相关资源
    最近更新 更多