仅在尚不存在的SQLite中创建表


Answers:


483

来自http://www.sqlite.org/lang_createtable.html

CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);

3
这也适用于指数:CREATE UNIQUE INDEX IF NOT EXISTS some_index ON some_table(some_column, another_column);
Michael Scheper

1
如果我想然后也只在不存在的情况下做一堆插入呢?我想要的是在我发现不存在的情况下动态创建派生表,而无需每次都花一堆REPLACE语句。
布里顿·凯林

1
@BrittonKerin,所以首先您必须检查表是否存在(这是我想的关键...其余的只是在执行条件检查后运行您的代码)。在这种情况下,请在答案中查看我的答复。
aaronlhe

1

我将尝试在这个非常好的问题上增加价值,并以@BrittonKerin的问题为基础,该问题来自@David Wolever的出色答案。想要在这里分享,因为我遇到了与@BrittonKerin相同的挑战,并且得到了一些有效的方法(即,仅在表不存在的情况下才想运行一段代码)。

        # 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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.