Created
September 16, 2019 14:49
-
-
Save ynux/1547148165ba1ca361d4dae19272e118 to your computer and use it in GitHub Desktop.
python code to count rows of all tables in a sqlite database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# python 3 | |
# what for: count rows of all tables in the main sqlite db | |
# caution: this overwrites the file test.csv | |
import sqlite3 | |
import sys | |
import subprocess | |
dbfile='/tmp/test.db' | |
filetype=subprocess.check_output(["file", dbfile], encoding="utf-8") | |
if "SQLite" not in filetype.split(":")[1]: | |
sys.exit('I am not convinced that {} is a valid sqlite database'.format(dbfile)) | |
table_rowcount={} | |
try: | |
conn = sqlite3.connect(dbfile) | |
cursor = conn.cursor() | |
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") | |
tables = cursor.fetchall() | |
for table in tables: | |
cursor.execute("select count(*) from {}".format(table[0])) | |
table_rowcount[table[0]]=cursor.fetchone()[0] | |
with open('test.csv', 'w') as f: | |
for key in table_rowcount.keys(): | |
f.write("%s,%s\n"%(key,table_rowcount[key])) | |
cursor.close() | |
except sqlite3.Error as error: | |
print("SQLite error: {}".format(error), file=sys.stderr) | |
except Exception as exc: | |
print(exc, file=sys.stderr) | |
finally: | |
if (conn): | |
conn.close() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment