Skip to content
Advertisement

How to check if table exists?

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?

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement