How to test if a table already exists?

conn = sqlite3.connect('sowpods.db')
curs = conn.cursor()
try:
    curs.execute('''CREATE TABLE spwords(sp_word TEXT, word_len INT, word_alpha TEXT,word_score INT)''')
    conn.commit()
except OperationalError: 
    None

https://docs.python.org/2/tutorial/errors.html

I believe if it already exists you can just skip the error and move directly into the inserting of the data


I am not a fan of the bounce the CREATE off the database approach. You should know whether the table exists so that first time initialization can occur.

Here is the same query based answer but based on general purpose functions:

def getTables(conn):
   """
   Get a list of all tables
   """
   cursor = conn.cursor()
   cmd = "SELECT name FROM sqlite_master WHERE type='table'"
   cursor.execute(cmd)
   names = [row[0] for row in cursor.fetchall()]
   return names

def isTable(conn, nameTbl):
   """
   Determine if a table exists
   """
   return (nameTbl in getTables(conn))

Now the top code is

if not(isTable(conn, 'spwords')):
    # create table and other 1st time initialization

The query you're looking for is:

SELECT name FROM sqlite_master WHERE type='table' AND name='spwords'

So, the code should read as follows:

tb_exists = "SELECT name FROM sqlite_master WHERE type='table' AND name='spwords'"
if not conn.execute(tb_exists).fetchone():
    conn.execute(tb_create)

A convenient alternative for SQLite 3.3+ is to use a more intelligent query for creating tables instead:

CREATE TABLE IF NOT EXISTS spwords (sp_word text, word_len int, word_alpha text, word_score int)

From the documentation:

It is usually an error to attempt to create a new table in a database that already contains a table, index or view of the same name. However, if the "IF NOT EXISTS" clause is specified as part of the CREATE TABLE statement and a table or view of the same name already exists, the CREATE TABLE command simply has no effect (and no error message is returned). An error is still returned if the table cannot be created because of an existing index, even if the "IF NOT EXISTS" clause is specified.

Tags:

Python

Sqlite