📜  如何使用Python给定 SQLite 表的行数?

📅  最后修改于: 2022-05-13 01:54:19.406000             🧑  作者: Mango

如何使用Python给定 SQLite 表的行数?

在本文中,我们将讨论如何使用Python给定 SQLite 表的行数。我们将使用cursor_obj.fetchall()方法来做同样的事情。此方法获取查询结果的所有行。它将所有行作为元组列表返回。如果没有要获取的记录,则返回一个空列表。

要创建数据库,我们将执行以下代码:

Python3
import sqlite3
  
# Connecting to sqlite
# connection object
connection_obj = sqlite3.connect('geek.db')
  
# cursor object
cursor_obj = connection_obj.cursor()
  
# Drop the GEEK table if already exists.
cursor_obj.execute("DROP TABLE IF EXISTS GEEK")
  
# Creating table
table = """ CREATE TABLE GEEK (
            Email VARCHAR(255) NOT NULL,
            Name CHAR(25) NOT NULL,
            Score INT
        ); """
  
cursor_obj.execute(table)
  
# inserting data into geek table
connection_obj.execute(
    """INSERT INTO GEEK (Email,Name,Score) VALUES ("geekk1@gmail.com","Geek1",25)""")
connection_obj.execute(
    """INSERT INTO GEEK (Email,Name,Score) VALUES ("geekk2@gmail.com","Geek2",15)""")
connection_obj.execute(
    """INSERT INTO GEEK (Email,Name,Score) VALUES ("geekk3@gmail.com","Geek3",36)""")
connection_obj.execute(
    """INSERT INTO GEEK (Email,Name,Score) VALUES ("geekk4@gmail.com","Geek4",27)""")
connection_obj.execute(
    """INSERT INTO GEEK (Email,Name,Score) VALUES ("geekk5@gmail.com","Geek5",40)""")
connection_obj.execute(
    """INSERT INTO GEEK (Email,Name,Score) VALUES ("geekk6@gmail.com","Geek6",14)""")
connection_obj.execute(
    """INSERT INTO GEEK (Email,Name,Score) VALUES ("geekk7@gmail.com","Geek7",10)""")
  
connection_obj.commit()
  
# Close the connection
connection_obj.close()


Python3
import sqlite3
  
# Connecting to sqlite
# connection object
connection_obj = sqlite3.connect('geek.db')
  
# cursor object
cursor_obj = connection_obj.cursor()
  
print("Count of Rows")
cursor_obj.execute("SELECT * FROM GEEK")
print(len(cursor_obj.fetchall()))
  
connection_obj.commit()
  
# Close the connection
connection_obj.close()


输出:



因此,通过查找由 fetchall() 返回的此列表的长度,我们得到总行数的计数。

蟒蛇3

import sqlite3
  
# Connecting to sqlite
# connection object
connection_obj = sqlite3.connect('geek.db')
  
# cursor object
cursor_obj = connection_obj.cursor()
  
print("Count of Rows")
cursor_obj.execute("SELECT * FROM GEEK")
print(len(cursor_obj.fetchall()))
  
connection_obj.commit()
  
# Close the connection
connection_obj.close()

输出: