我正在执行 SELECT 查询。我正在得到一个结果集。 问题是如果我迭代一次,我就无法再次迭代。我认为计数器需要重新初始化。但我做不到。
在我的代码中,第一个 FOR 循环正在运行,但第二个则不起作用。请帮忙。
我在 stackoverflow 上搜索过这个问题,但找不到任何答案
代码
类 ItemList(资源):
def get(self):
connection = sqlite3.connect("data.db")
cursor = connection.cursor()
select_query = "SELECT * FROM items"
rows = cursor.execute(select_query)
items=[]
for row in rows:
print(row)
if rows:
for row in rows:
items.append({'name':row[0],'price':row[1]})
connection.commit()
connection.close()
return {'items':items},200
预期结果是 [{'name': '椅子', 'price': 23.456}, {'name': 'table', 'price': 3333}, {'name': 'van', 'price': 1234}] 对于项目数组
最佳答案
如果您“将游标视为迭代器”,如此处所做的那样 rows =cursor.execute(select_query)
,它会在幕后执行“fetch”操作”。
来自sqlite3 API doc [添加强调]:
To retrieve data after executing a SELECT statement, you can either treat the cursor as an iterator, [or] call the cursor’s fetchone() method to retrieve a single matching row, or call fetchall() to get a list of the matching rows.
如果将 rows =cursor.execute(select_query)
更改为 rows=cursor.execute(select_query).fetchall()
,rows
将是一个包含结果的数组,您可以根据需要对其进行多次迭代。
关于python - 如何重新初始化sqlite3中SELECT查询结果集中的行索引计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56139018/