0

Is there a way to test for the existence of a table in a SQLite database? Right now, I'm creating the table inside a try catch block, and if that throws an exception I know the table has been created. Surely there has to be a better way, right?

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Geo
  • 93,257
  • 117
  • 344
  • 520

2 Answers2

7

To detect if a particular table exists, use:

SELECT name 
  FROM sqlite_master
 WHERE type = 'table'
   AND name LIKE '%your_table_name%'
OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
4

There is a table called sqlite_master that contains the database schema. You can run a query like:

select count(*) from sqlite_master where name='users';

If the query returns 1, the table 'users' exists. You can also use the if not exists SQL construction:

create table if not exists users (name, pwd);
David Crawshaw
  • 10,427
  • 6
  • 37
  • 39