Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a table already exists?

Tags:

python

sqlite

I'm working on a scrabblecheat program

Following some examples I have the following code below which uses SQLite for a simple database to store my words.

However it tells me I can't recreate the database table.

How do I write in a check for if there is already a table named spwords, then skip trying to create it?

The error:

(<class 'sqlite3.OperationalError'>, OperationalError('table spwords already exists',), None)

The Code:

def load_db(data_list):

# create database/connection string/table
conn = sqlite.connect("sowpods.db")

#cursor = conn.cursor()
# create a table
tb_create = """CREATE TABLE spwords
                (sp_word text, word_len int, word_alpha text, word_score int)
                """
conn.execute(tb_create)  # <- error happens here
conn.commit()

# Fill the table
conn.executemany("insert into spwords(sp_word, word_len, word_alpha, word_score) values (?,?,?,?)",  data_list)
conn.commit()

# Print the table contents
for row in conn.execute("select sp_word, word_len, word_alpha, word_score from spwords"):
    print (row)

if conn:
    conn.close()
like image 596
Leon Gaban Avatar asked Oct 27 '13 19:10

Leon Gaban


People also ask

How do you check that table is already exists?

To check if a table exists in SQL Server, you can use the INFORMATION_SCHEMA. TABLES table. You can use this table with an IF THEN clause do determine how your query responds whether or not a table exists.

How do you check if a table already exists in SQL?

Using the OBJECT_ID and the IF ELSE statement to check whether a table exists or not. Alternative 2 : Using the INFORMATION_SCHEMA. TABLES and SQL EXISTS Operator to check whether a table exists or not.

How can you tell if a table is present in a database?

If the user is SYSTEM or has access to dba_tables data dictionary view, then use the given below query: Query: SELECT owner, table_name FROM dba_tables; This query returns the following list of tables that contain all the tables that are there in the entire database.

How do you know if data exists in one table and not in another?

We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.


1 Answers

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.

like image 71
BartoszKP Avatar answered Oct 10 '22 04:10

BartoszKP