How to test if a table already exists?

前端 未结 3 1986
北荒
北荒 2020-12-09 12:11

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.

Ho

3条回答
  •  半阙折子戏
    2020-12-09 12:46

    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
    

提交回复
热议问题