簡體   English   中英

python mysql select只返回表的第一行,而不是全部

[英]python mysql select return only first row of table, not all

我正在處理奇怪的問題,這是這樣的:

此查詢應返回我的所有表:

db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
cursor.execute("select * from mytable")
cursor.fetchall()
for row in cursor:
print row

for 循環應該打印游標中的所有行,但它只會打印第一行。 似乎游標只填充了第一行。

有什么我在這里錯過的嗎? 謝謝

您需要將 cursor.fetchall() 的輸出放入一個變量中。 喜歡

db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
cursor.execute("select * from mytable")
rows = cursor.fetchall()
for row in rows:
    print row

嘗試

db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
for row in cursor.execute("select * from mytable"):
    print row

你需要一個 dic 並將結果保存在這里

dic={}
cursor.execute("select * from table")
dic['table']=cursor.fetchall()
for row in range(len(dic['table'])):
    print dic['table'][row]

如果您需要打印任何列

print dic['table'][row]['colum']

這不是使用.fetchall()方法的正確方法。 使用cursor.stored_results()然后對結果執行fetchall()以執行此任務,如下所示:

db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
cursor.execute("select * from mytable")
results = cursor.stored_results()
for result in results:
    print result.fetchall()

您可以嘗試限制

cursor.execute("select * from mytable limit 1")

我也有這個問題。 我的錯誤是在表中插入新行后我沒有提交結果。 所以你應該在 INSERT 命令之后添加 db.commit() 。

我知道它已經很長時間了,但我沒有在其他任何地方找到這個答案,並認為它可能會有所幫助。

cursor.execute("SELECT top 1 * FROM my_table")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM