Python MySQLdb iterate through table

放肆的年华 提交于 2019-12-03 05:41:18

This will set the cursor at the beginning of the result set and tell you how many rows it got back (I went back and forth on this one, but this is the most authoritative documentation I have found, older Python MySQLdb lib returned rowcount on execute, but Python Database API Specification v2.0 does not, this should be the most compatible)

cursor.execute("SELECT user_id FROM round WHERE state = -1 OR state = 2")
numrows = cursor.rowcount

Will tell you how many Rows you got in return

for x in xrange(0,numrows):
  row = cursor.fetchone()
  print row[0], "-->", row[1]

Will iterate over each row (no need to enumerate x with range)

Dvd Avins

Once you have results in the cursor, you can iterate right in it.

cursor = database.cursor()    
cursor.execute("SELECT user_id FROM round WHERE state == -1 AND state = 2")  
for round in cursor:
  if round[0] != 5
    ...do stuff
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!