简体   繁体   English

遍历python中mysql中的行

[英]Iterating through the rows in mysql in python

I have a mysql database table consisting of 8 columns as given 我有一个由8列组成的mysql数据库表

ID   C1    C2    C3    C4    C5    C6    C7 

1    25    33    76    87    56    76    47
2    67    94    90    56    77    32    84
3    53    66    24    93    33    88    99
4    73    34    52    85    67    82    77
5    78    55    52   100    78    68    32
6    67    35    60    93    88    53    66

I need to fetch 3 rows of all the column except the ID column at a time. 我需要一次获取除ID列之外的所有列的3行。 So far I did this code in python which fetches me the rows with ID values 1,2,3. 到目前为止,我已经在python中完成了此代码,该代码将ID值分别为1,2,3的行提取给了我。

ex = MySQLdb.connect(host,port,user,passwd,db)
with ex:
 ex_cur = ex.cursor()
 ex.execute("SELECT C1,C2,C3,C4,C5,C6,C7 FROM table LIMIT 0, 3;") 

In the second cycle I need to fetch rows with ID values 2,3,4, third cycle fetches rows with ID values 3,4,5 which should continue till the end of the database. 在第二个周期中,我需要获取ID值为2、3、4的行,第三个周期则获取ID值为3、4、5的行,该行应持续到数据库结束。 What query should I use to iterate through the table so as to get the desired set of rows. 我应该使用哪种查询来遍历表,以获得所需的行集。

I believe there are three ways of doing this: (I'm going to explain at a very high level) 我相信可以通过以下三种方式进行此操作:(我将在较高级别上进行解释)

  1. You can create a queue with a size limit of 3 and read in the rows as a stream. 您可以创建大小限制为3的队列,并将其作为流读入行中。 Once the queue reaches the max size of 3, do your processing, pop off the first element in your queue, and proceed with the stream. 队列达到最大大小3后,进行处理,弹出队列中的第一个元素,然后继续处理流。 (More efficient) (更高效)

  2. You would need an iterator and reset your cursor for every set of 3 IDs that you have to do. 您将需要一个迭代器,并为每组3个ID重置光标。

  3. Since your table is relatively small (would not suggest this for larger tables), load the whole database into a data structure/into memory. 由于您的表相对较小(对于较大的表,则不建议这样做),因此将整个数据库加载到数据结构/内存中。 Perhaps make an object for the rows and use an ORM to map rows to objects. 也许为行创建对象,然后使用ORM将行映射到对象。 Then you would simply have to iterate through each object, or set of 3 objects, and do the necessary processing. 然后,您只需要遍历每个对象或一组3个对象,并进行必要的处理即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM