仅在SQLite中不存在时才在SQLite中创建表

时间:2010-11-04 15:04:16

标签: sqlite create-table database-table

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

2 个答案:

答案 0 :(得分:415)

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

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

答案 1 :(得分: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