如何在python中从sqlite表中获取数据行数
我试图获取python中sqlite3数据库返回的行数,但该功能似乎不可用: 想想如何在python中从sqlite表中获取数据行数,python,sqlite,Python,Sqlite,我试图获取python中sqlite3数据库返回的行数,但该功能似乎不可用: 想想phpmysqli\u num\u rows()中的mysql 虽然我设计了一种方法,但这是一个棘手的问题:假设一个类执行sql,并给出结果: # Query Execution returning a result data = sql.sqlExec("select * from user") # run another query for number of row checking, not very go
php
mysqli\u num\u 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")
是否有一个函数或属性可以在没有压力的情况下执行此操作。通常情况下,会提供查询结果的数量
但是,对于SQLite,由于SQLite生成结果的性质,该属性通常设置为-1。如果不先进行COUNT()
查询,您通常不知道返回的结果数
这是因为SQLite在数据库中找到行时会生成行,并且在到达数据库末尾之前,它自己不知道生成了多少行
从cursor.rowcount
的文档中:
尽管sqlite3
模块的Cursor
类实现了该属性,但数据库引擎本身对确定“受影响的行”/“选定的行”的支持却很奇怪
对于executemany()
语句,修改的数量汇总为rowcount
根据Python DB API规范的要求,如果未对游标执行executeXX()
,或者接口无法确定最后一个操作的行数,rowcount
属性“为-1”这包括SELECT
语句,因为在获取所有行之前,我们无法确定查询生成的行数。
我的
对于特定查询,可以添加子选择以添加列:
data = sql.sqlExec("select (select count() from user) as count, * from user")
然而,对于大型表来说,这并不是那么有效
如果只需要一行,请改用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"])
使用以下内容:
dataCopy = sql.sqlExec("select count(*) from user")
values = dataCopy.fetchone()
print values[0]
len(results)正是您想要的这里一个简单的替代方法是使用fetchall将列拉入python列表,然后计算列表的长度。我不知道这是肾盂手术还是特别有效,但似乎有效:
rowlist = []
c.execute("SELECT {rowid} from {whichTable}".\
format (rowid = "rowid", whichTable = whichTable))
rowlist = c.fetchall ()
rowlistcount = len(rowlist)
print (rowlistcount)
这个代码对我有用:
import sqlite3
con = sqlite3.connect(your_db_file)
cursor = con.cursor()
result = cursor.execute("select count(*) from your_table") #returns array of tupples
num_of_rows = result[0][0]
我发现带有count()的select语句在一个非常大的DB上运行缓慢。此外,使用
fetch all()
可能会占用大量内存
除非显式地设计数据库,使其不具有rowid,否则始终可以尝试快速解决方案
cur.execute("SELECT max(rowid) from Table")
n = cur.fetchone()[0]
这将告诉您数据库有多少行。如果您只想事先估计,请简单使用COUNT() 要在提取之前获取准确的数字,请使用锁定的“”,在此期间,表不会从外部更改,如下所示:
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)
注意:正常的
SELECT
也会锁定,但直到它本身被完全提取或光标关闭或commit()
/END
或其他操作隐式结束事务…以下脚本工作:
def say():
global s #make s global decleration
vt = sqlite3.connect('kur_kel.db') #connecting db.file
bilgi = vt.cursor()
bilgi.execute(' select count (*) from kuke ') #execute sql command
say_01=bilgi.fetchone() #catch one query from executed sql
print (say_01[0]) #catch a tuple first item
s=say_01[0] # assign variable to sql query result
bilgi.close() #close query
vt.close() #close db file
我喜欢这样做
cursor.execute("select count(*) from my_table")
results = cursor.fetchone()
print(results[0])
data.rowcount
returned-1data.COUNT()
returnedAttributeError:'sqlite3.Cursor'对象没有属性'COUNT'
@Temitayo:COUNT()
是一个SQL函数,而不是游标上的函数。选择(从用户选择COUNT())作为COUNT,*从用户选择“
使用此查询几乎解决了这个问题,虽然还有一些事情我需要弄清楚,但尝试拉出第一行并拉出计数,而不迭代数据data[0][“count”]
返回TypeError:'sqlite3.Cursor'对象不可下标
@Temitayo:不,您可以使用Cursor.fetchall()
一次性获取所有行,或者使用cursor.fetchone()
只获取您想要的结果,第一行。很好,但我想在做任何事情之前确定行数,如果我不知道如何fetchall
?您需要为问题添加标签,以获取视图对于大型表,这是非常低效的。对于大型表,这是非常低效的,我永远不会使用这种方法来确定表的行数。我有一个包含7706455行的表(由selectcount(*)报告)…
但是最大行ID
是96171095196!继我之前的评论之后,我实际上给出了一个糟糕的示例,但我仍然说不应该使用此方法来获取行数。请看。如果您在不使用真空
的情况下从表中删除行,您将得到不正确的总数。
def say():
global s #make s global decleration
vt = sqlite3.connect('kur_kel.db') #connecting db.file
bilgi = vt.cursor()
bilgi.execute(' select count (*) from kuke ') #execute sql command
say_01=bilgi.fetchone() #catch one query from executed sql
print (say_01[0]) #catch a tuple first item
s=say_01[0] # assign variable to sql query result
bilgi.close() #close query
vt.close() #close db file
cursor.execute("select count(*) from my_table")
results = cursor.fetchone()
print(results[0])