2013-06-26 76 views
0

IM處理strage問題,這是這樣的:蟒蛇MySQL的選擇只返回第一行的表,並不是所有

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

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循環應該打印光標中的所有行,但它只會打印第一個。 它看起來光標只填滿了第一行。

有什麼我錯過了嗎? 謝謝

回答

1

您需要將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 
+0

沒有區別,我仍然得到第一行:( – user1229351

0

嘗試

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 
+0

它爲cursor.execute(「select * from mytable」)中的行返回錯誤: TypeError:'long'對象不可迭代「 – user1229351

0

你需要一個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'] 
0

這不是正確的方式使用.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() 
0

你可以試試 「LIMIT」 cursor.execute( 「SELECT * FROM mytable的極限1」)

0

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

相關問題