如何在python中从sqlite3数据库中获取数据行数

Tem*_*ayo 5 python sqlite

我试图获取从python中的sqlite3数据库返回的行数,但似乎该功能不可用:

想想php mysqli_num_rows()mysql

虽然我设计了一种方法,但它很尴尬:假设一个类执行sql并给我结果:

# Query Execution returning a result
data = sql.sqlExec("select * from user")
# run another query for number of row checking, not very good workaround
dataCopy = sql.sqlExec("select * from user")
# Try to cast dataCopy to list and get the length, I did this because i notice as soon 
# as I perform any action of the data, data becomes null
# This is not too good as someone else can perform another transaction on the database 
# In the nick of time
    if len(list(dataCopy)) :
        for m in data :
            print("Name = {}, Password = {}".format(m["username"], m["password"]));
    else :
        print("Query return nothing")
Run Code Online (Sandbox Code Playgroud)

是否有能够在没有压力的情况下做到这一点的功能或属性.

小智 7

import sqlite3
conn = sqlite3.connect(path/to/db)
cursor = conn.cursor()
cursor.execute("select * from user")
results = cursor.fetchall()
print len(results)
Run Code Online (Sandbox Code Playgroud)

len(results) 正是你想要的

  • 对于大表,这是非常低效的。 (5认同)

Mar*_*ers 6

通常,cursor.rowcount会给出查询结果的数量.

但是,对于SQLite,由于SQLite生成结果的性质,该属性通常设置为-1.短的COUNT()查询第一,你经常会不知道返回结果的数量.

这是因为SQLite在数据库中找到行时会生成行,并且在达到数据库末尾之前本身不会知道生成了多少行.

来自以下文件cursor.rowcount:

虽然模块的Cursorsqlite3实现了这个属性,但数据库引擎自己支持确定"受影响的行"/"选择的行"是古怪的.

对于executemany()陈述,修改的数量总结为rowcount.

根据Python DB API Spec的要求,rowcount如果没有executeXX()对游标执行或者最后一个操作的rowcount不能被接口确定,则属性"为-1 ".这包括SELECT语句,因为在获取所有行之前,我们无法确定查询生成的行数.

强调我的.

对于您的特定查询,您可以添加子选择以添加列:

data = sql.sqlExec("select (select count() from user) as count, * from user")
Run Code Online (Sandbox Code Playgroud)

然而,对于大型表来说,这并不是那么有效.

如果你需要的是一个排,使用cursor.fetchone()来代替:

cursor.execute('SELECT * FROM user WHERE userid=?', (userid,))
row = cursor.fetchone()
if row is None:
    raise ValueError('No such user found')

result = "Name = {}, Password = {}".format(row["username"], row["password"])
Run Code Online (Sandbox Code Playgroud)


kxr*_*kxr 6

当您只想预先估计时,只需使用 COUNT():

n_estimate = cursor.execute("SELECT COUNT() FROM user").fetchone()[0]
Run Code Online (Sandbox Code Playgroud)

要在获取之前获取确切的数字,请使用锁定的“读取事务”,在此期间表不会从外部更改,如下所示:

cursor.execute("BEGIN")  # start transaction
n = cursor.execute("SELECT COUNT() FROM user").fetchone()[0]
# if n > big: be_prepared()
allrows=cursor.execute("SELECT * FROM user").fetchall()
cursor.connection.commit()  # end transaction
assert n == len(allrows)
Run Code Online (Sandbox Code Playgroud)

注意:普通SELECT也会锁定 - 但直到它本身被完全获取或游标关闭或commit()/END或其他操作隐式结束事务......


use*_*866 5

使用以下:

dataCopy = sql.sqlExec("select count(*) from user")
values = dataCopy.fetchone()
print values[0]
Run Code Online (Sandbox Code Playgroud)


小智 5

我发现带有 count() 的 select 语句在非常大的数据库上很慢。此外,使用fetch all()可能非常占用内存。

除非你明确设计你的数据库使其没有rowid,否则你总是可以尝试快速解决方案

cur.execute("SELECT max(rowid) from Table")
n = cur.fetchone()[0]
Run Code Online (Sandbox Code Playgroud)

这将告诉您数据库有多少行。