-1

I am writing logs in mysql database and I create a table coordinates, with the columns Id, x, y. When I want to read from the db, I want to print the latest log each time:

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

It always returns the first row in the log which is not ordered by DESC. It seems that fetchall changes the order of the log. Is there any solution?

gus27
  • 2,616
  • 1
  • 21
  • 25
SillyPerson
  • 589
  • 2
  • 7
  • 30

1 Answers1

0

Your code returns only last row because you requested for only 1 item:

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

Since, you have already mentioned in the query ORDER BY id DESC, it will return value based on decreasing order of id. May be you checked the wrong data.

Also, you print just the value of x, because again your code asked for that:

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

In order to get all the values of both x and y, do:

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

# OR,
# for row in cursor.fetchall():
#     print("x= ", row[0], ", y= ", row[1]) 
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126