python - how to check if table exists?

Use the "TABLES" information schema view. http://dev.mysql.com/doc/refman/5.0/en/information-schema.html

SELECT * FROM information_schema.tables
WHERE table_name = 'YOUR TABLE'

You can apply this view to your code by doing something like the following:

def checkTableExists(dbcon, tablename):
    dbcur = dbcon.cursor()
    dbcur.execute("""
        SELECT COUNT(*)
        FROM information_schema.tables
        WHERE table_name = '{0}'
        """.format(tablename.replace('\'', '\'\'')))
    if dbcur.fetchone()[0] == 1:
        dbcur.close()
        return True

    dbcur.close()
    return False

Above answer might not work for Oracle, I found code snippet below work for Oracle:

import cx_Oracle
def checkTableExists(dbcon, tablename):
    dbcur = dbcon.cursor()
    try:
        dbcur.execute("SELECT * FROM {}".format(tablename))
        return True
    except cx_Oracle.DatabaseError as e:
        x = e.args[0]
        if x.code == 942: ## Only catch ORA-00942: table or view does not exist error
            return False
        else:
            raise e
    finally:
        dbcur.close()

If you are using Python-MySQL (MySQLdb) -> http://mysql-python.sourceforge.net/MySQLdb.html

cursor.execute() is the method to run queries with MySQLdb, Python MySQL driver. You can pass two arguments, like:

cursor.execute(statement, parameters)

And will execute "statement" parsing "parameters" to the statement. You need to have opened a database connection and also open a cursor

I think you can use MySQL's statement: SHOW TABLES LIKE 'tablename';

stmt = "SHOW TABLES LIKE 'tableName'"
cursor.execute(stmt)
result = cursor.fetchone()
if result:
    # there is a table named "tableName"
else:
    # there are no tables named "tableName"

EDIT: there will other Python drivers with similar behaviour. Look for yours :)

Tags:

Python

Sql