LightingLong 2025-01-17 20:07 采纳率: 83.3%
浏览 7
已结题

Python sqlite fetchone时不显示全部

img


如图,为什么表格里面有两行数据,fetchone时只显示一条?

  • 写回答

2条回答 默认 最新

  • 檀越@新空间 2025-01-17 20:15
    关注

    晚上好🌙🌙🌙
    本答案参考通义千问

    当你使用 fetchone() 方法从 SQLite 数据库中检索数据时,它每次调用只会返回一行数据。如果你期望获取多行数据,那么你需要多次调用 fetchone() 或者改用 fetchall() 方法来一次性获取所有结果。

    让我们通过一个具体的例子来理解这一点:

    假设你有一个名为 example.db 的数据库,并且该数据库有一个名为 users 的表,其中包含以下数据:

    | id | name | |----|-------| | 1 | Alice | | 2 | Bob |

    你可以使用以下 Python 脚本来查询这个表,并解释为什么 fetchone() 只返回一行数据。

    示例代码

    import sqlite3
    
    # 连接到 SQLite 数据库
    connection = sqlite3.connect('example.db')
    
    # 创建一个游标对象
    cursor = connection.cursor()
    
    # 执行 SQL 查询
    cursor.execute("SELECT * FROM users")
    
    # 使用 fetchone() 获取一行数据
    row = cursor.fetchone()
    print(row)  # 输出: (1, 'Alice')
    
    # 再次使用 fetchone() 获取下一行数据
    row = cursor.fetchone()
    print(row)  # 输出: (2, 'Bob')
    
    # 如果再次调用 fetchone(),将会返回 None,因为没有更多的行了
    row = cursor.fetchone()
    print(row)  # 输出: None
    

    解决方案

    1. 多次调用 fetchone():如果你需要获取多行数据,可以多次调用 fetchone()

      import sqlite3
      
      connection = sqlite3.connect('example.db')
      cursor = connection.cursor()
      cursor.execute("SELECT * FROM users")
      
      while True:
          row = cursor.fetchone()
          if row is None:
              break
          print(row)
      
    2. 使用 fetchall() 获取所有行

      import sqlite3
      
      connection = sqlite3.connect('example.db')
      cursor = connection.cursor()
      cursor.execute("SELECT * FROM users")
      
      rows = cursor.fetchall()
      for row in rows:
          print(row)
      
    3. 使用列表推导式(如果你更喜欢简洁的写法):

      import sqlite3
      
      connection = sqlite3.connect('example.db')
      cursor = connection.cursor()
      cursor.execute("SELECT * FROM users")
      
      rows = [row for row in cursor]
      for row in rows:
          print(row)
      

    总结

    • fetchone() 每次调用只返回一行数据,直到所有数据都被读取完毕。
    • fetchall() 会一次性返回所有行的数据。
    • 根据你的需求选择合适的方法来处理查询结果。
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 1月26日
  • 已采纳回答 1月18日
  • 创建了问题 1月17日