我有一个使用 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 Workbench 运行完全相同的查询,返回的结果是:
我不知道为什么这两个查询会返回不同的结果。我还使用下面的 wireshark 查看了网络流量信息,但我没有明确的理由为什么会这样。
最佳答案
您必须在获取下一行之前打印该行,如下所示:
while row is not None:
print(row)
row = cursor.fetchone()
关于Python MySQL 连接器无法从 SELECT 查询返回所有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28270884/