如何在 sqlite3 中的 SELECT 查询的结果集中重新初始化行索引计数?
how to re-initialize the row index count in result set of a SELECT query in sqlite3?
我正在执行 SELECT 查询。我得到了一个结果集。
问题是如果我迭代一次,我无法迭代 Again.I 认为计数器需要重新初始化。但是我做不到。
在我的代码中,第一个 FOR 循环有效,但第二个无效。请帮助。
我已经在 Whosebug 上搜索过这个但是我找不到任何答案
代码
class 物品列表(资源):
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': 'chair', 'price': 23.456}, {'name': 'table', 'price': 3333}, {'name': 'van', 'price': 1234}]
对于项目数组
如果您 "treat the cursor as an iterator",就像这里 rows = cursor.execute(select_query)
所做的那样,它会 fetch
ing "under the hood"。
来自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
将是一个包含结果的数组,您可以根据需要对其进行多次迭代。
我正在执行 SELECT 查询。我得到了一个结果集。 问题是如果我迭代一次,我无法迭代 Again.I 认为计数器需要重新初始化。但是我做不到。
在我的代码中,第一个 FOR 循环有效,但第二个无效。请帮助。
我已经在 Whosebug 上搜索过这个但是我找不到任何答案
代码
class 物品列表(资源):
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': 'chair', 'price': 23.456}, {'name': 'table', 'price': 3333}, {'name': 'van', 'price': 1234}] 对于项目数组
如果您 "treat the cursor as an iterator",就像这里 rows = cursor.execute(select_query)
所做的那样,它会 fetch
ing "under the hood"。
来自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
将是一个包含结果的数组,您可以根据需要对其进行多次迭代。