【问题标题】:Web.py sql query, why we can only traverse the result at the first time?web.py sql查询,为什么我们只能在第一时间遍历结果?
【发布时间】:2023-04-03 00:18:01
【问题描述】:

这是我的代码:

import web
user_db = web.database(dbn='mysql', ....)

info_list = user_db.query("select * from tablename where t_id= ")
for info in info_list:
# work ok at first time, print the correct id
    print info.id

for info in info_list: 
# Code can't reach here 
    print info.id

每个的第二次似乎都行不通。为什么?

【问题讨论】:

  • @alecxe 它有效,谢谢。你能解释一下为什么吗?

标签: python mysql database web.py


【解决方案1】:

根据source code,底层的query() 调用返回一个迭代器,在第一个循环之后它会被耗尽。

如果您需要多次迭代,请将其转换为列表:

info_list = list(user_db.query("select * from tablename where t_id= "))

或者,您可以使用itertools.tee() 创建新的迭代器:

info_list1, info_list2 = itertools.tee(info_list)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 2016-10-21
    • 2015-05-05
    相关资源
    最近更新 更多