Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the numbers of data rows from sqlite table in python

Tags:

python

sqlite

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.

like image 444
Temitayo Avatar asked Feb 17 '14 12:02

Temitayo


People also ask

How do I count rows in SQLite?

In SQLite the Count(*) function will return total number of rows available in a table, including the rows which contain NULL values. The Count(*) will not take any parameters other than the asterisk symbol (*).

How do I get table information in SQLite?

If you are running the sqlite3 command-line access program you can type ". tables" to get a list of all tables. Or you can type ". schema" to see the complete database schema including all tables and indices.

How many rows can a SQLite table have?

The theoretical maximum number of rows in a table is 264 (18446744073709551616 or about 1.8e+19). This limit is unreachable since the maximum database size of 281 terabytes will be reached first.


2 Answers

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

len(results) is just what you want

like image 95
WeizhongTu Avatar answered Nov 15 '22 15:11

WeizhongTu


When you just want an estimate beforehand, then simple use COUNT():

n_estimate = cursor.execute("SELECT COUNT() FROM user").fetchone()[0]

To get the exact number before fetching, use a locked "Read transaction", during which the table won't be changed from outside, like this:

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)

Note: A normal SELECT also locks - but just until it itself is completely fetched or the cursor closes or commit() / END or other actions implicitely end the transaction ...

like image 30
kxr Avatar answered Nov 15 '22 15:11

kxr