仅在SQLite中创建表,前提是它不';不存在

仅在SQLite中创建表,前提是它不';不存在,sqlite,create-table,database-table,Sqlite,Create Table,Database Table,我只想在SQLite数据库中创建一个不存在的表。有没有办法做到这一点?如果表存在,我不想删除它,只有当它不存在时才创建它。来自: 我将尝试为这个非常好的问题增加价值,并在@David Wolever的精彩答案下的一条评论中,以@BrittonKerin的问题为基础。我想在这里分享,因为我遇到了与@BrittonKerin相同的挑战,我得到了一些有用的东西(即,只想在表不存在的情况下运行一段代码) 可能的重复也适用于索引:如果不存在,则创建唯一索引某些表上的某些索引(某些列,另一列)如果我想在不存

我只想在SQLite数据库中创建一个不存在的表。有没有办法做到这一点?如果表存在,我不想删除它,只有当它不存在时才创建它。

来自:


我将尝试为这个非常好的问题增加价值,并在@David Wolever的精彩答案下的一条评论中,以@BrittonKerin的问题为基础。我想在这里分享,因为我遇到了与@BrittonKerin相同的挑战,我得到了一些有用的东西(即,只想在表不存在的情况下运行一段代码)


可能的重复也适用于索引:
如果不存在,则创建唯一索引某些表上的某些索引(某些列,另一列)如果我想在不存在的情况下也进行一系列插入,怎么样?我想要的是,如果我发现一个派生表不存在,就可以动态地创建它,而不必每次支付一堆REPLACE语句的费用。@BrittonKerin,因此首先你必须检查该表是否存在(我想这是关键……其余的只是在执行条件检查后运行你的代码)。在这个条件下,请务必在答案中看到我的回答。
CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);
        # 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