python - 如何重新初始化sqlite3中SELECT查询结果集中的行索引计数?

标签 python mysql database sqlite flask-restful

我正在执行 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/

相关文章:

python - 针对多个类名的 assertIsInstance()

python - 切片 numpy 数组与选择单个元素

mysql - 如何循环遍历表的所有行? (MySQL)

mysql - 类似 SQL 的按钮

python - 名称错误 : global name 'dot_parser' is not defined

python - HTML Flask 按钮无法正确重定向到主页 URL

mysql - CodeIgniter数据库错误覆盖

database - 将 excel 电子表格转换为可查询数据库的最佳/最简单方法

mysql - mysql无法连接sequel pro

python - 使用 Oracle 客户端和 Kerberos 与 Python 连接到数据库