Criar uma tabela no SQLite apenas se já não existir

só quero criar uma tabela numa base de dados SQLite se já não existir. Há alguma maneira de fazer isto? Eu não quero deixar cair a mesa se ela existir, apenas criá-la se ela não existir.

Author: davidism, 2010-11-04

2 answers

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

CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);
 519
Author: David Wolever, 2018-06-01 17:21:02
{[[2]} vou tentar adicionar valor a esta pergunta muito boa e desenvolver a pergunta de @BrittonKerin em um dos comentários sob a fantástica resposta de @David Wolever. Queria compartilhar aqui porque eu tinha o mesmo desafio que @ BrittonKerin e eu tenho algo funcionando (ou seja, só quero executar um pedaço de código apenas se a tabela não existir).
        # 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
 1
Author: aaronlhe, 2020-05-31 08:47:21