How to check if table exists?

Question:

I’m using this function :

def checker(name,s)
        MY_T = "SELECT count(*) FROM `"+session.SessionInfo.Name where EventName='"+name+"'"

I want to check if the table exists, how can I do it?

I saw some examples using XXXX.execute(). What does it mean?

Here is what I saw:

query = cursor.execute("""SELECT count(*) FROM scan WHERE prefix = %s and code_id = %s and answer = %s and station_id = %s""",
                          (prefix, code_id, answer, station,))
        if query != 1:

I tried printing MY_T to see if it returns -1 for example but it just prints "select count (*)...... "

How can I check it?

Asked By: user1386966

||

Answers:

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
Answered By: feathj

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 🙂

Answered By: Alberto Megía

I found that this works well with Python 3.6 and MySql 5.7:

table = 'myTable'
_SQL = """SHOW TABLES"""
cursor.execute(_SQL)
results = cursor.fetchall()

print('All existing tables:', results) # Returned as a list of tuples

results_list = [item[0] for item in results] # Conversion to list of str

if table in results_list:
    print(table, 'was found!')
else:
    print(table, 'was NOT found!')
Answered By: Jens M.

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()
Answered By: Wendao Liu

I think the most straightforward way is using:

SELECT COUNT(*) = 1 as exists FROM pg_tables WHERE tablename = 'my_table';

that returns if table exists:

 exists 
--------
 t
(1 row)

or in Python using psycopg2:

cur.execute(
    """
    SELECT COUNT(*) = 1 FROM pg_tables WHERE tablename = 'my_table';
    """
)
exists = cur.fetchone()[0]
print(exists)
True
if exists is False:
   # table does not exist
   ...
Answered By: tuned

try this code
it shows all tables. then, compare the saved tables name to your target table

change cursor to yours in your code ^_^

def tableExistance(table_name):

    cursor.execute('SHOW tables;')

    myresult = cursor.fetchall()

    for loacal_table_name in myresult:

        print('table name', loacal_table_name[0])
    
        if loacal_table_name[0] == table_name:
        
            return True
    
    return False

exist = tableExistance("you table name")
print('tableExistance', exist)
Answered By: Kamal Zaitar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.