Create table in SQLite only if it doesn't exist already

后端 未结 2 1599
醉梦人生
醉梦人生 2020-11-28 21:24

I want to create a table in a SQLite database only if doesn\'t exist already. Is there any way to do this? I don\'t want to drop the table if it exists, only create it if it

相关标签:
2条回答
  • 2020-11-28 21:45

    Am going to try and add value to this very good question and to build on @BrittonKerin's question in one of the comments under @David Wolever's fantastic answer. Wanted to share here because I had the same challenge as @BrittonKerin and I got something working (i.e. just want to run a piece of code only IF the table doesn't exist).

            # for completeness lets do the routine thing of connections and cursors
            conn = sqlite3.connect(db_file, timeout=1000) 
    
            cursor = conn.cursor() 
    
            # get the count of tables with the name  
            tablename = 'KABOOM' 
            cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))
    
            print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.
    
            # check if the db has existing table named KABOOM
            # if the count is 1, then table exists 
            if cursor.fetchone()[0] ==1 : 
                print('Table exists. I can do my custom stuff here now.... ')
                pass
            else: 
               # then table doesn't exist. 
               custRET = myCustFunc(foo,bar) # replace this with your custom logic
    
    0 讨论(0)
  • 2020-11-28 22:03

    From http://www.sqlite.org/lang_createtable.html:

    CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);
    
    0 讨论(0)
提交回复
热议问题