简体   繁体   English

使用数据库时,迭代器如何工作?

[英]How do Iterators act when working with databases?

Making queries like SELECT * FROM people could create serious memory problems, ie, as many like to call it, "memory exceeded". 进行诸如SELECT * FROM people这样的查询可能会导致严重的内存问题,即,许多人都称其为“内存超出”。

Many programmers invoke using iterators to reduce memory consumption. 许多程序员调用使用迭代器来减少内存消耗。 Iterators are a sort of "play-n-pause video recording", meaning that they procuce a value, they stop, they produce a value and so on, avoiding to generate all the values all at once. 迭代器是一种“播放n暂停视频记录”,这意味着它们产生一个值,停止,产生一个值,依此类推,避免一次生成所有的值。 An example in Python could be the following: Python中的示例如下:

def myIterator():
  for i in range(10):
    yield i * 2

Now, when it comes to use iterators to fetch data from databases, I get pretty confused. 现在,当涉及到使用迭代器从数据库中获取数据时,我感到非常困惑。 I was always told to limit the number of queries toward a database because it could become a bottleneck and, using iterators, it seems to me to increment the number of queries. 总是被告知要限制对数据库的查询数量,因为它可能成为瓶颈,而且在我看来,使用迭代器来增加查询数量。 Is it so? 是这样吗? How does an iterator work with database queries? 迭代器如何与数据库查询一起使用? Is this the well-known problem of the short bed sheet, again? 这又是短床单的众所周知的问题吗? In addition, what happens if, during the fetch phase with an iterators, some data is added in the database? 另外,如果在使用迭代器的访存阶段中,一些数据添加到数据库中,会发生什么情况?

PS My question isn't related to a particular programming language, but it is in general. PS我的问题与特定的编程语言无关,但总的来说。

RDBMS comes to help when using iterators. 使用迭代器时,RDBMS可以提供​​帮助。 DB client sends a request, to which DB replies with the first batch of rows; 数据库客户端发送一个请求,数据库以第一批行答复该请求; once the client acknowledges the receipt, the server stops sending, and waits. 客户端确认收据后,服务器将停止发送并等待。

DB client library lets the program that uses iterators "digest" the data, until the program iterates past what's already buffered. DB客户端库允许使用迭代器的程序“消化”数据,直到该程序迭代经过已缓冲的内容为止。 At that point it asks RDBMS to continue sending the data. 此时,它要求RDBMS继续发送数据。

It is up to the program to decide what to do with the data. 由程序决定如何处理数据。 If it does not store the whole thing in memory, it uses up only as much data as is buffered by DB client. 如果它没有将全部内容存储在内存中,则它仅使用与DB客户端缓冲的一样多的数据。

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

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