Python MySQLdb遍历表 [英] Python MySQLdb iterate through table

查看:134
本文介绍了Python MySQLdb遍历表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MSQL数据库,并且需要遍历表并在满足WHERE子句后执行操作.然后,当它到达表格的末尾时,返回顶部并重新开始.

I have a MSQL db and I need to iterate through a table and perform an action once a WHERE clause is met. Then once it reaches the end of the table, return to the top and start over.

当前我有

cursor = database.cursor()    
cursor.execute("SELECT user_id FROM round WHERE state == -1 AND state = 2")  
round_id = cursor.fetchone()

if round != 5
   ...do stuff

循环,但这显然只会循环第一个条目.我想您需要使用for in函数来读取表,但是我不确定如何使用mysqldb来做到这一点?

in a loop but this obviously only keeps looping the first entry. I guess you need to use the for in function to read through the table, but I'm not sure exactly how to do this using mysqldb?

推荐答案

这会将光标设置在结果集的开头,并告诉您它返回了多少行(我在这一行上来回走了,但是这是最权威的文档,我发现,返回了较旧的Python MySQLdb lib执行时执行rowcount,但是Python Database API Specification v2.0却没有,这应该是最兼容的)

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

会告诉您返回了多少行

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

将遍历每一行(无需用范围枚举x)

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

这篇关于Python MySQLdb遍历表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆