I am trying to get the numbers of rows returned from an sqlite3 database in python but it seems the feature isn't available:
Think of php
mysqli_num_rows()
in mysql
Although I devised a means but it is a awkward: assuming a class execute sql
and give me the results:
# 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")
Is there a function or property that can do this without stress.
len(results) is just what you want
I've found the select statement with count() to be slow on a very large DB. Moreover, using
fetch all()
can be very memory-intensive.Unless you explicitly design your database so that it does not have a rowid, you can always try a quick solution
This will tell you how many rows your database has.
A simple alternative approach here is to use fetchall to pull a column into a python list, then count the length of the list. I don't know if this is pythonic or especially efficient but it seems to work:
this code worked for me:
Normally,
cursor.rowcount
would give you the number of results of a query.However, for SQLite, that property is often set to -1 due to the nature of how SQLite produces results. Short of a
COUNT()
query first you often won't know the number of results returned.This is because SQLite produces rows as it finds them in the database, and won't itself know how many rows are produced until the end of the database is reached.
From the documentation of
cursor.rowcount
:Emphasis mine.
For your specific query, you can add a sub-select to add a column:
This is not all that efficient for large tables, however.
If all you need is one row, use
cursor.fetchone()
instead:Use following: