2016-11-23 68 views
-1

我在mysql數據庫中寫入日誌,我創建了一個表coordinates,列Id,x,y。當我想從數據庫中讀取,我想每次打印最新的日誌:打印表格行mysql python

cursor.execute("Select x,y from coordinates ORDER BY id DESC LIMIT 1") 
for row in cursor.fetchall(): 
    print(row[0]) 

它總是返回第一行未通過DESC下令在日誌中。看來,fetchall更改日誌的順序。有沒有解決方法?因爲你的要求只有1項

+0

你如何識別它返回的第一行而不是最後一行? – gus27

回答

0

你的代碼只返回最後一行:

"Select x,y from coordinates ORDER BY id DESC LIMIT 1" 
# You asked your database to return just one record^

,因爲你在查詢ORDER BY id DESC已經提到的,它會根據遞減ID的順序返回值。可能你檢查了錯誤的數據。

此外,您打印的x只是價值,因爲再次代碼要求是:

for row in cursor.fetchall(): 
    print(row[0]) 
    #  ^item at 0th index  

爲了得到這兩個xy的所有值,這樣做:

for x, y in cursor.fetchall(): 
    print("x= ", x, ", y= ", y) 

# OR, 
# for row in cursor.fetchall(): 
#  print("x= ", row[0], ", y= ", row[1])