SavinI
SavinI

Reputation: 318

How could I check - does my SQLite3 database is empty?

I am using Python 2.7 and SQLite3. When I starting work with DB I want to check - does my database is empty or on not. I mean does it already have any tables or not.

My idea is to use the simple SELECT from any table. And wrap this select in try:exception block. So if exception was raised then my DB is empty.

Maybe someone know the better way for checking?

Upvotes: 5

Views: 3574

Answers (2)

dimo414
dimo414

Reputation: 48824

This doesn't directly answer your question, but I prefer to use the user_version for the purpose of efficiently sanity-checking my database. Whenever I create a DB I set the user_version to a non-zero value (generally starting with 1 and incrementing as I make breaking changes to the schema) alongside my CREATE TABLE calls and associated bootstrapping. This helps me know not only that my DB is not empty but also that it's initialized as I expect. If the user_version is different than expected I can return an error or apply a schema migration to the supported version.

Obviously this only works for DBs you created/own. If you're trying to inspect the contents of an arbitrary DB sqlite_master is the way to go.

Upvotes: 1

Nullman
Nullman

Reputation: 4279

SELECT name FROM sqlite_master

while connected to your database will give you all the tables names. you can then do a fetchall and check the size, or even contents of the list. not try/catch necessary (the list will be empty if the database doesn't contain any tables)

Upvotes: 7

Related Questions